Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart pointer blows stack due to recursive delete

Simple data structures, for instance linked lists, where the 'next' pointer is a smart pointer. When the head node gets deleted, the smart pointer for 'next' kicks in and does a recursive delete. For a long list, this quickly blows the stack.

I have had to go back to replace these smart pointers with simple, raw pointers. Am I missing something here?

like image 682
Jay Avatar asked Aug 20 '11 10:08

Jay


1 Answers

Assuming I've understood you right and both head and next are smart pointers you can avoid this by doing:

head = head->next;

Or equivalent. Your 'old' head will get deleted and the old second place item will get promoted to the head. All in one consistent change, with no deep recursion. The only pre-condition to this is that head is not NULL to begin with.

As Mike pointed out in the comment if the goal is to delete the whole list then you can repeat that within a loop.

like image 172
Flexo Avatar answered Sep 20 '22 08:09

Flexo