7

What would happen if I called std::move twice with the same unique_ptr ?

unique_ptr<int> foo(new int(5));
unique_ptr<int> bar = move(foo);
unique_ptr<int> baz = move(foo);

PS: No, std::unique_ptr usage is NOT the same question. Both questions are about unique_ptr, and this is the only common thing between them.

user31264
  • 6,557
  • 3
  • 26
  • 40

2 Answers2

14

Moving from a unique_ptr leaves it as null. So baz will end up being null too.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
9

Essentially, nothing. The standard library requires that moving a library type leaves it in a valid but unspecified state. By valid they mean you can still do things to the object that don't require a precondition. That would be things like assigning it a new value or destroying it. For unique_ptr we actually get more of a guarantee of the state as the move constructor guarantees that the moved from object is set to nullptr. That means in the end of all of this bar holds the pointer and foo and baz are both nullptr.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402