简体   繁体   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.... 
}

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 /( leftchildrightchild )设置正确的smartPointer( std::shared_ptr / std::weak_ptr或指针/ std::unique_ptr )。

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

相关问题 什么应该在适当的析构函数? - What should be in a proper destructor? 在析构函数中删除单链表的正确方法是什么? - What is the proper way to delete a singly-linked-list in destructor? 用openssl构建静态二进制文件的正确方法是什么? - What is the proper way of building a static binary with openssl? 问:编写这个类的析构函数的正确和安全的方法是什么? - Qt: What is the correct and safe way to write the destructor of this class? 当您具有二维数组(在C ++中)时,调用析构函数的正确方法是什么? - What's the proper way to call a destructor when you have a two-dimensional array (in C++)? 调用析构函数以释放C ++运算符中的内存的正确方法是什么? - What is the proper way to call the destructor to free up memory in a C++ operator? 引用类的成员函数的正确方法是什么? - What is the proper way to reference a member function of a class? 通用二叉树节点析构函数问题 - Generic binary tree node destructor issue 节点和二叉树构造函数和析构函数Segfaulting - Node and Binary Tree Constructor and Destructor Segfaulting 如果派生类析构函数抛出异常,基类析构函数会发生什么 - What happens to base class destructor if a derived class destructor throws an exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM