I see below notes in std::unique_ptr
reference:
Only non-const
unique_ptr
can transfer the ownership of the managed object to anotherunique_ptr
. The lifetime of an object managed by conststd::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.
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 during 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).
The reset
, release
, swap
, and move assignment functions are non-const member functions and therefore cannot be used with a const instance of the std::unique_ptr
class. Therefore, a const std::unique_ptr
has no way of being modified and is forced to own the pointer until it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With