c++ 释放包含自定义 class 的向量的内存

c++ release memory of vector containing custom class

我想手动释放vector的内存。 vector 的元素是自定义 class。

我用谷歌搜索清楚了,shrink_to_fit 就可以了。但它不适用于自定义向量 class 和整数向量。

下面是自定义的测试代码和定义class.

using namespace std;
class HandsDisQuality{
public:
    unordered_map<Hands,float,HandsHash> handsdis;
    // handslist is the keys of handsdis
    std::vector<Hands> handslist;

    HandsDisQuality();
    HandsDisQuality(std::vector<Hands>& v);
    HandsDisQuality(unordered_map<Hands,float,HandsHash>& inputhandsdis);
    HandsDisQuality(float range);
    void init(unordered_map<Hands,float,HandsHash>& inputhandsdis);
    float operator[](Hands& key);
    float get(Hands& key, float defaultvalue);
    float sum();
    int size();
    void removecard(Card& card);
    void removecard(Hands & hand, vector<Card> & board);

    bool normalize();
    void printdata(char sep = '\t');
    std::vector<Hands> * gethands();
    Json::Value tojson();
    void loadfromjson(Json::Value & jsonvalue);
    void test();
    static vector<HandsDisQuality> Generateophands(vector<float> oprange);
    static vector<HandsDisQuality> Generateophands(float oprange);
};

int main() {
vector<HandsDisQuality> v(500000,HandsDisQuality(0.3));
// 14GB
    cout << "init over"<<endl;
    char a;
    cin >> a;
    v.clear();
// 14GB
    cout << "after clear"<<endl;
    cin >> a;
    v.shrink_to_fit();
// 14GB
    cout << "release memory"<<endl;
    cin >> a;
}

int main() {
vector<int> v(500000000,0);
// 2.34GB
    cout << "init over"<<endl;
    char a;
    cin >> a;
    v.clear();
// 2.34GB
    cout << "after clear"<<endl;
    cin >> a;
    v.shrink_to_fit();
// 400MB
    cout << "release memory"<<endl;
    cin >> a;
}

真要清内存就得换了:

v.swap(vector<HandsDisQuality>());

shrink_to_fit不用缩水,不绑定:

It is a non-binding request to reduce capacity() to size(). It depends on the implementation whether the request is fulfilled.