0

Let me try to elaborate it.

Stack Frame: When we execute any function it create stack where all local variables and instructions reside.
And Smart Pointer: smart pointer like std::unique_ptr allows to change ownership of object inside of smart pointer.

Now my confusion is: suppose we pass a unique_ptr from a source function to a target function, the rvalue will be assigned to target pointer by std::move. Now if the function exits, the stack frame will deallocated. So will unique_ptr in target function be a dangling pointer, since unique_ptr is pointing to same memory location that resides in source function's stack frame?

One thing I thought is, since target function lifetime will be over before source function's lifetime. So that wont cause any such side effects. But in more complex applications with multi threaded environment, how does it go? Or what do we need to take care of?

3

You're conflating two things: scope, which governs the lifetime of objects, and stack frames, which are an implementation detail, and aren't relevant here.

Now my confusion is suppose we pass unique_ptr from source function to target function, The rvalue will be assigned to target pointer by std::move

So you've explicitly moved ownership from the caller's unique_ptr object (in the source function) to the callee's unique_ptr (in the target function). The source's unique_ptr object no longer owns anything, and you can't dereference it.

Now, when the target function returns (or throws an exception - anything that causes its scope to exit), and the target's unique_ptr object is destroyed, it will delete the object previously owned by the caller's unique_ptr.

Control then returns to the source function, whose unique_ptr is still in scope but no longer owns anything. There's nothing you can usefully do with this object except assign it a new pointer to control.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.