[英]What is the proper way to make a destructor for this binary node class?
class node{
private:
node* parent;
node* leftchild;
node* rightchild;
// etc....
}
I don't want to create an infinite cycle with destructor that's why I'm interested how can I make a good constructor for it. 我不想用析构函数创建无限循环,这就是为什么我感兴趣的我该如何为它构造一个好的构造函数。
Calling delete
on a pointer that is NULL
will not call the destructor. 在
NULL
指针上调用delete
不会调用析构函数。
Just set the nodes to NULL
in constructor, and only allocate them if they are supposed to exist. 只需在构造函数中将节点设置为
NULL
,并仅在它们应该存在的情况下才分配它们。
So its safe to delete the sub-objects in the destructor, cause the 'chain' will stop when it reaches a child-node that is NULL
. 因此,可以安全地删除析构函数中的子对象,从而导致“链”在到达子节点
NULL
时停止。
Example: 例:
#include <iostream>
class Node{
public:
Node() {
node = NULL;
}
~Node() {
std::cout << "Deleting" << std::endl;
delete node;
}
void CreateChildNode() {
node = new Node();
}
private:
Node* node;
};
int main()
{
Node *n = new Node();
n->CreateChildNode();
delete n;
return 0;
}
Above code snippet will output: 上面的代码片段将输出:
Deleting 删除
Deleting 删除
I would say: 我会说:
node::~node()
{
// remove reference to this from neighboor.
if (leftchild) {
leftchild->parent = nullptr;
}
if (rightchild) {
rightchild->parent = nullptr;
}
if (parent) {
if (parent->leftchild == this) {
parent->leftchild = nullptr;
} else {
parent->rightchild = nullptr;
}
}
}
And the correct smartPointer ( std::shared_ptr
/ std::weak_ptr
or pointer/ std::unique_ptr
) for parent
/( leftchild
, rightchild
). 并
parent
/( leftchild
, rightchild
)设置正确的smartPointer( std::shared_ptr
/ std::weak_ptr
或指针/ std::unique_ptr
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.