user2580104
user2580104

Reputation:

Does unique_ptr automatically destruct when not referenced?

Similar to the concept of GC in Java, when an object is not referenced anymore by something else, it gets marked for GC.

Does unique_ptr work similar to this?

If say I have a data structure (a tree) with nodes containing left/right std::unique_ptr<BSTNode>. Say I have a remove function remove(std::unique_ptr<BSTNode>& root, int val), if I go to the parent of the BSTNode containing val, and assign nullptr to the left or right child field (which is the std::unique_ptr<BSTNode> containing val), would the smart pointer self destruct?

Or should I reset the smart pointer inside of the remove function as well? This question is mostly a scope issue that I am not understanding.

Upvotes: 1

Views: 3861

Answers (2)

Andy Dent
Andy Dent

Reputation: 17969

The key to unique_ptr is understanding the lifespan of stack variables.

There's nothing inherent in unique_ptr that's different from other stack variables, just the use of its destructor to clean up the owned content. This is an idiom widely used before these pointers, referred to as RAII Resource Acquisition Is Initialisation.

If you have a unique_ptr on the stack, ie: declared inside some scope, it executes its destructor when you exit that scope and the stack variables are deleted.

If you have it inside some struct or class allocated on the heap, it executes its destructor when that container is deleted.

Upvotes: 3

if I go to the parent of the BSTNode containing val, and assign nullptr to the left or right child field (which is the std::unique_ptr containing val), would the smart pointer self destruct?

The smart pointer will destroy the thing it points to.

It will not destroy itself (which is what self-destruct means; you may have confused terminology here).

Upvotes: 2

Related Questions