n元树结构的析构函数
Destructor of an n-ary tree struct
我有以下代码:
const int MAXCHILD = 10;
struct Node {
Node *child[10];
Node();
void deleteNode(Node *n);
~Node();
};
Node::Node() {
for(int i=0; i<MAXCHILD; i++) {
child[i] = NULL;
}
}
void Node::deleteNode(Node *n) {
if(n == NULL) {
return;
} else {
for(int i=0; i<MAXCHILD; i++) {
deleteNode(n->child[i]);
}
for(int i=0; i<MAXCHILD; i++) {
n->child[i] = NULL;
}
}
n = NULL;
}
Node::~Node() {
Node *n = this;
deleteNode(n);
}
int main() {
Node *n = new Node();
...
delete n;
n = NULL;
return 0;
}
这就是我尝试过的
我在编译/测试时没有遇到任何严重错误,但当我用Valgrind测试内存泄漏时,它表明我一直在进行内存泄漏。
我知道我的析构函数有很多缺陷;会有什么问题
提前谢谢!
内存泄漏是由您从未释放子级引起的
(将指针设置为NULL
是不够的。)
你的析构函数可以这么简单:
Node::~Node() {
for(int i=0; i<MAXCHILD; i++) {
delete child[i];
child[i] = nullptr;
}
}
内存泄漏的另一个原因也可能是递归生成或构造子节点。如果您在结构内部更改子数据字段,并以不同的方式管理它,比如在构造函数内部以某种方式携带它,或者在外部链接子字段和父字段,效果会更好。试试看,它可能会让你摆脱内存泄漏
相关文章:
- 未调用的初始化静态thread_local结构的构造函数和析构函数
- 为什么添加析构函数(甚至是空的)会破坏我的结构,该结构使用 ref 转发和折叠来保存 ref 或值的副本?
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- 为什么结构与auto_ptr和显式析构函数无法交换
- 程序结构以捕获SIGINT并在C++中调用析构函数
- 关于结构构造函数和析构函数行为-C++
- 未调用静态全局结构的析构函数
- 带有指针的C++结构:构造函数和析构函数
- 设计一个没有虚拟析构函数的多态类层次结构
- 为C++结构定义显式析构函数如何影响调用约定
- 结构sqlite3的sqlite3c++正向声明导致析构函数中删除时出现无效指针错误
- 树结构的C++析构函数
- 如果在派生类中定义了虚拟析构函数,但不是层次结构的顶部,该怎么办?C++
- 涉及类和结构的构造函数/析构函数
- 结构中的析构函数和c++中的类
- 在赋值运算符之前调用了结构的析构函数
- 结构对象析构函数
- 在公共层次结构中的类之间共享析构函数
- 结构体中指针数组的析构函数
- 继承层次结构:构造函数和析构函数执行顺序