I participate in C ++ SWE training and build a simple LinkedList class using std :: unique_ptr as references to head and next . This is the basic structure:
template <class T> struct LinkedListNode { T value; std::unique_ptr<LinkedListNode<T>> next; // For debugging. ~LinkedListNode() { std::cout << "destructed for value " << this->value << std::endl; } }; template <class T> struct LinkedList { std::unique_ptr<LinkedListNode<T>> head; };
Using smart pointers, I expect that when a LinkedList instance is deleted or out of scope, then the head will be deleted, and each next node will also be deleted recursively.
And this is exactly what is happening. However, when working with really long lists (~ 20M nodes), this surprisingly still works fine. Shouldn't it crash due?
To very roughly estimate the size of my OS stack, I wrote the following script:
int main() { struct s { static void p(int i) { std::cout << i << std::endl; p(i+1); }; s::p(0); }
And it crashed on iteration number ~ 175K, much smaller than the 20M nodes that I could free earlier. What's happening? Am I missing something about how unique_ptr works?
source share