ExBen ExBen - 2 months ago 19
C++ Question

lifetime of an object managed by const std::unique_ptr

I see below notes in

reference:


Only non-const
unique_ptr
can transfer the ownership of the managed object to another
unique_ptr
. The lifetime of an object managed by const
std::unique_ptr
is limited to the scope in which the pointer was created.


Is there anyone who can explain it with an example? I could not figure it out why.

Answer

You simply can not move from a const std::unique_ptr and you can't use other modifying member functions - swap, release and reset either (these are logically non-const qualified, cannot be called on a const instance).

Transferring ownership implies resetting the old owner to non-owning state, thus modifying it.


const std::unique_ptr will manage at most one object through its lifetime (starting from its initialization).
In case of std::unique_ptr const&, you won't be able to transfer ownership from the referenced (even non-const) std::unique_ptr through this reference (const correctness).