Kingston Chan Kingston Chan - 1 year ago 43
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

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

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

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

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

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 Source

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.