C++ std::unique_ptr Lifetime Explained: Why Return Values Don't Trigger Destruction
Understanding std::unique_ptr Lifetime and Ownership
When working with modern C++ smart pointers, developers often wonder about the exact lifetime of dynamically allocated objects—especially when returning a std::unique_ptr from a function. If a std::unique_ptr is created within a local function scope, why doesn't its destructor run immediately when that function exits?
The short answer lies in ownership transfer and move semantics.
The Core Concept: Ownership Transfer
std::unique_ptr enforces exclusive ownership over a dynamically allocated resource. Only one std::unique_ptr can own a given resource at any time. When you return a local std::unique_ptr by value from a function, ownership of the resource is transferred (moved) out of the function and handed over to the caller.
Because ownership is transferred to the calling scope, the local variable inside the function gives up its handle to the object before exiting. As a result, no destruction happens when the function scope ends.
Step-by-Step Code Execution Flow
Let's trace the execution of the code to see what happens under the hood: