这个C++容器的析构函数哪里出错了
Where am I getting wrong in the destructor for this C++ container?
我正在处理一个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;
}
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 如何正确使用 >=?(a+f()+c)>=0 错了吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 指针相关的UE4崩溃.我的指针哪里错了?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 我在尝试将多个值push_back向量时出错。我做错了什么?
- 过载时出错 <<。我在这里做错了什么?
- 使用针对Win32的英特尔C++编译器编译Qt时出错,我做错了什么