Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unique_ptr guaranteed to store nullptr after move?

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? 
like image 869
lizarisk Avatar asked Jun 05 '14 13:06

lizarisk


People also ask

What happens to unique_ptr after move?

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.

Can Make_unique return nullptr?

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.

What happens when unique_ptr goes out of scope?

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.

Can you set unique_ptr to nullptr?

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 .


1 Answers

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 pointer u2. Upon completion of such a transfer, the following postconditions hold:
u2.p is equal to the pre-transfer u.p,
u.p is equal to nullptr, and
...

(the member p is described earlier as — a unique pointer is an object u that stores a pointer to a second object p)

like image 97
Praetorian Avatar answered Sep 18 '22 16:09

Praetorian