Kingston Chan Kingston Chan - 2 months ago 5
C++ Question

Does default destructor free the memory pointed by the member pointers?

When I delete a node in a linked list, do I need to set the

next
to NULL?

The ListNode is defined as this

struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x) {}
}


Now I wanna delete the node after
m


ListNode *tmp = m->next;
m->next = m->next->next;
delete tmp;


If
tmp->next
would be deleted in the destructor, the linked list should be in trouble. However, if
tmp->next
is not deleted, there could be another case that causes memory leak:

ListNode *tmp = new ListNode(0);
tmp->next = new ListNode(1);
delete tmp;


If
tmp->next
is not deleted, there's no way to find this piece of memory again.

So it's a dilemma here, what does the default destructor actually do?

Answer

The default destructor destroys all member variables (that have destructors) and does nothing else.

None of ListNode's member variables have destructors, so the default destructor for ListNode does nothing.

Note that while next is a member variable, the thing next points to isn't.