Back to questionsWhy is
JuniorTheoryCommon
Why is std::unique_ptr move-only and how do you transfer ownership through APIs?
unique_ptr is exclusive ownership; copy would give two owners and double-delete. Copy ops deleted, move ops defined. Transfer: unique_ptr<T> by value (caller std::moves) or unique_ptr<T>&&. Borrow with T&/const T&. Return by value — move via RVO.
- Trying to assign
unique_ptrto another withoutstd::move— compile error - Passing
unique_ptr<T>&and modifying it in the callee unexpectedly - Using
unique_ptr<T>for borrowing — confuses ownership semantics
- How does
std::move(uniquePtr)differ fromuniquePtr.release()? - Why is
unique_ptrzero-overhead compared to a raw pointer?