Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does moving leave the object in a usable state?

Tags:

Say I have two vectors and I move one unto the other, v1 = std::move(v2); will v2 still be in a usable state after this?

like image 450
Paul Manta Avatar asked Oct 28 '11 13:10

Paul Manta


People also ask

What does move () do in C++?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t .

Does STD move invalidate pointers?

No. An object still exists after being moved from, so any pointers to that object are still valid.

Does STD copy move?

std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.

What is std :: move doing?

std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.


1 Answers

From n3290, 17.6.5.15 Moved-from state of library types [lib.types.movedfrom]

  1. Objects of types defined in the C++ standard library may be moved from (12.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

Since the state is valid, this means you can safely operate on v2 (e.g. by assigning to it, which would put it back to a known state). Since it is unspecified however, it means you cannot for instance rely on any particular value for v2.empty() as long as it is in this state (but calling it won't crash the program).

Note that this axiom of move semantics ("Moved from objects are left in a valid but unspecified state") is something that all code should strive towards (most of the time), not just the Standard Library components. Much like the semantics of copy constructors should be making a copy, but are not enforced to.

like image 106
Luc Danton Avatar answered Sep 21 '22 17:09

Luc Danton