ExBen ExBen - 5 months ago 34
C++ Question

lifetime of an object managed by const std::unique_ptr

I see below notes in


Only non-const
can transfer the ownership of the managed object to another
. The lifetime of an object managed by const
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.


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).