Is unique_ptr
guaranteed to store nullptr
after move?
std::unique_ptr<int> p1{new int{23}}; std::unique_ptr<int> p2{std::move(p1)}; assert(!p1); // is this always true?
A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.
Creating a unique pointer as std::unique_ptr<T> myptr; doesn't allocate any memory, so you don't need to construct it and pass nullptr at all. So you can just create one and return it. nullptr is a keyword new in C++11 for better support of null pointers. unique_ptr can be constructed from nullptr , even implicitly.
unique_ptr. An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope.
This means that the definition of class template unique_ptr<> includes an overload of operator = that accepts a value of type nullptr_t (such as nullptr ) as its right hand side; the paragraph also specifies that assigning nullptr to a unique_ptr is equivalent to resetting the unique_ptr .
Yes, you can compare it to nullptr
after the move
and it is guaranteed to compare equal.
From §20.8.1/4 [unique.ptr]
Additionally,
u
can, upon request, transfer ownership to another unique pointeru2
. Upon completion of such a transfer, the following postconditions hold:
—u2.p
is equal to the pre-transferu.p
,
—u.p
is equal tonullptr
, and
...
(the member p
is described earlier as — a unique pointer is an object u
that stores a pointer to a second object p
)
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