Christian
Christian

Reputation: 831

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:

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.


Question:

Upvotes: 1

Views: 434

Answers (2)

Corristo
Corristo

Reputation: 5510

The proper way is to not use owning raw pointers, use std::unique_ptr for the children instead.

If you also get rid of the superfluous typedef, the struct looks like this:

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.

Upvotes: 3

florgeng
florgeng

Reputation: 886

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.

Upvotes: 1

Related Questions