79
votes

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?
2
Technically the state in which ::move leaves an element is unspecified. I don't think there is any guarantee on the smart pointer's end either. That said, I'll leave it to the CPP experts to answer :)Benjamin Gruenbaum
Wait, never mind, yes. Release explicitly sets it to nullptr. This is guaranteed by the unique_ptrBenjamin Gruenbaum
gcc 4.8.1 here, p1 is null after the std::moveExceptyon
just look at move semantics...Deduplicator

2 Answers

72
votes

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)

11
votes

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