Is unique_ptr guaranteed to store nullptr after move?

C++C++11Move SemanticsUnique Ptr

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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)

Solution 2 - C++

Yes. From C++2011 Standard Section 20.7.1/4:

> Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold [...] [the source unique_ptr] is equal to nullptr...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlizariskView Question on Stackoverflow
Solution 1 - C++PraetorianView Answer on Stackoverflow
Solution 2 - C++Paul EvansView Answer on Stackoverflow