我正在处理 a map
,其第二个元素也是 a map
,其第二个元素是 a vector
。在地图构建过程中,似乎我必须动态分配内存,但后来我无法正确释放内存。我的问题可以简化为下面的源代码。
我只是无法弄清楚为什么析构函数不正确。
另外,在这种情况下有没有更好的方法来避免内存泄漏?
#include <vector>
#include <map>
#include <iostream>
using namespace std;
typedef vector<int> IntVect;
typedef map<int, IntVect> NumEle;
typedef map<int, NumEle> Nums;
class NumLess {
public:
Nums numSet;
~NumLess() {
for (Nums::iterator I = numSet.begin(), E = numSet.end(); I != E; ++I) {
NumEle &numEle = I->second;
for (NumEle::iterator II = numEle.begin(), EE = numEle.end(); II != EE; ++II) {
IntVect &intVect = II->second;
intVect.clear();
delete &intVect;
}
delete &numEle;
}
}
friend ostream &operator<<(ostream &os, const NumLess &numLess) {
for (Nums::const_iterator I = numLess.numSet.begin(),
E = numLess.numSet.end();
I != E; ++I) {
const NumEle &numEle = I->second;
os << "NumEle:" << I->first << endl;
for (NumEle::const_iterator II = numEle.begin(), EE = numEle.end();
II != EE; ++II) {
os << "IntVect " << II->first << " | ";
const IntVect &intVect = II->second;
for (auto i : intVect) {
os << i << " ";
}
os << endl;
}
}
return os;
}
};
int main(void) {
NumLess numLess;
for (unsigned h = 4; h > 0; --h) {
NumEle *numEle = new NumEle();
for (unsigned i = h; i > 0; --i) {
IntVect *intVect = new IntVect();
for (unsigned j = 0; j < i; ++j) {
intVect->push_back(j);
}
numEle->insert(pair<int, IntVect>(i, *intVect));
}
numLess.numSet.insert(pair<int, NumEle>(h, *numEle));
}
cout << numLess;
cout << "finished" << endl;
return 0;
}