문제

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