Does moving the object leave usable state?

Let's say I have two vectors, and I move one to the other, v1 = std::move(v2) ; will v2 still be in usable state after that?

+14
c ++ c ++ 11 move-semantics
Oct 28 '11 at 13:46
source share
2 answers

From n3290, 17.6.5.15 Moving from the state of library types [lib.types.movedfrom]

  • Type objects defined in the C ++ standard library can be moved from (12.8). Move operations can be explicitly specified or implicitly generated. Unless otherwise specified, such relocated objects are placed in a valid but undefined state.

Since the state is valid, this means that you can safely work with v2 (for example, by assigning it to which will return it to a known state). Since this is not indicated, this means that you cannot, for example, rely on any specific value for v2.empty() while it is in this state (but calling it will not cause the program to crash).

Please note that this axiom of movement semantics ("Moved from objects remains in a valid, but undefined state") is what all the code (in most cases) should aim for, and not just the components of the standard library. Like the semantics of copy constructors, a copy must be made, but not respected.

+19
Oct 28 2018-11-11T00:
source share

No, he is left in an unspecified state.

Excerpt from open-std-org -

.. move () gives its purpose the value of its argument, but is not required to maintain the value of its source . Thus, for the vector move (), one would reasonably expect its argument to become a vector of zero capacity in order to avoid the need to copy all the elements. In other words, moving is a potentially destructive read.

+6
Oct 28 '11 at
source share



All Articles