简体   繁体   English

如何破坏包含自指指针的对象?

[英]How to destruct object containing self-referential pointer?

I have a tree node structure which is simply defined as: 我有一个树节点结构,其简单定义为:

typedef struct TreeNode {
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode *parent;

    TreeNode(int);
    ~TreeNode();
} TreeNode;

To free memory pointed by the left , right , and parent objects upon destruction (assuming not null), I made a destructor as follows: 为了释放leftrightparent对象在销毁时所指向的内存(假设不为null),我按如下方式构造了一个析构函数:

TreeNode::~TreeNode() {
    delete left;
    delete right;
    delete parent;
}

However, doing so causes the control to infinitely recursively delete the TreeNode objects since those delete statements inside the destructor calls the destructor of the same structure. 但是,这样做会导致控件无限递归地删除TreeNode对象,因为析构函数中的那些delete语句将调用同一结构的析构函数。


Question: 题:

  • What is the proper way of freeing self-referential pointers, specifically inside the destructor? 释放自我引用指针的正确方法是什么,尤其是在析构函数内部?

The proper way is to not use owning raw pointers, use std::unique_ptr for the children instead. 正确的方法是不使用拥有的原始指针,而对子代使用std::unique_ptr

If you also get rid of the superfluous typedef , the struct looks like this: 如果您还摆脱了多余的typedef ,则该结构如下所示:

struct TreeNode {
    int data;
    std::unique_ptr<TreeNode> left;
    std::unique_ptr<TreeNode> right;
    TreeNode *parent{nullptr};

    TreeNode() = default;
};

Now you don't need to do anything, the compiler will generate the correct deconstructor for you. 现在您无需执行任何操作,编译器将为您生成正确的解构函数。

It should work if you don't call the parent destructor. 如果您不调用父析构函数,它应该可以工作。 But then, as mentioned above, the entire tree below that node will be deleted. 但是,如上所述,该节点下的整个树将被删除。

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

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