繁体   English   中英

为该二进制节点类构造析构函数的正确方法是什么?

[英]What is the proper way to make a destructor for this binary node class?

class node{

private:
node* parent;
node* leftchild;
node* rightchild;
// etc.... 
}

我不想用析构函数创建无限循环,这就是为什么我感兴趣的我该如何为它构造一个好的构造函数。

NULL指针上调用delete不会调用析构函数。
只需在构造函数中将节点设置为NULL ,并仅在它们应该存在的情况下才分配它们。

因此,可以安全地删除析构函数中的子对象,从而导致“链”在到达子节点NULL时停止。

例:

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

上面的代码片段将输出:
删除
删除

我会说:

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

parent /( leftchildrightchild )设置正确的smartPointer( std::shared_ptr / std::weak_ptr或指针/ std::unique_ptr )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM