I'm having some confusion about memory de-allocation in C++. I have a structure

struct Node{
    Node* left;
    Node* right;
};

and I declare a pointer of Node type as:

struct Node* myNode = new Node;

Now if I do a delete myNode does it also de-allocates the left and right pointer inside myNode? If it doesn't, wouldn't it be very tedious if we have a lot of pointers inside Node type and will be very difficult to write code without memory leakage?

有帮助吗?

解决方案

No it wont destruct or deallocate them. However, for such cases you can write a destructor:

~Node()
{
    delete left;
    delete right;
}

An even better approach would be to use smart pointer like std::shared_ptr or std::unique_ptr

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top