-1

我正在处理 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;
}
4

1 回答 1

1

To make a long story very short : you are deleting object that you didn't allocate. To fix it, you need to remove deletes from your destructor.

You also have a leak in your main. You are creating objects on heap, and never releasing. The created objects are copied into the containers. To fix this leak, remove new, and just add objects into containers.


If you prefer to work with pointers (bad in my opinion), you need to change your typedefs :

typedef map<int, IntVect*> NumEle;
typedef map<int, NumEle*> Nums;

Here is 'main()' without 'new' and memory leak :

int main(void) {
  NumLess numLess;
  for (unsigned h = 4; h > 0; --h) {
    NumEle numEle;
    for (unsigned i = h; i > 0; --i) {
      IntVect 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;
}
于 2013-08-31T14:12:03.373 回答