这个C++容器的析构函数哪里出错了

Where am I getting wrong in the destructor for this C++ container?

本文关键字:出错 错了 析构函数 C++ 这个      更新时间:2023-10-16

我正在处理一个map,它的第二个元素也是map,它的第一个元素是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;
}

长话短说:您正在删除未分配的对象。要修复它,您需要从析构函数中删除删除项。

你的主管道也有泄漏。您在堆上创建对象,而从不释放。创建的对象将复制到容器中。要修复此泄漏,请删除新对象,然后将对象添加到容器中。


如果你喜欢使用指针(在我看来不好),你需要更改你的typedefs:

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

这里是没有"new"和内存泄漏的"main()":

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;
}