Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lifetime of an object managed by const std::unique_ptr

I see below notes in std::unique_ptr 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.

like image 741
ExBen Avatar asked Nov 30 '22 16:11

ExBen


2 Answers

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

like image 52
LogicStuff Avatar answered Dec 04 '22 03:12

LogicStuff


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.

like image 27
James Adkison Avatar answered Dec 04 '22 03:12

James Adkison