Touloudou
Touloudou

Reputation: 2223

What is technically a moved-from object?

According to the standard, you can only do certain things with moved-from objects. However, what is technically considered a moved-from objects?

let's say I do this:

int x = 42;
std::move(x);
int y = x; // is this ok?

std::move is just a cast to a rvalue-reference. If this reference is not consumed, does that count as a move? Could I still use x in the example above, after the call to std::move?

Upvotes: 0

Views: 172

Answers (1)

ALX23z
ALX23z

Reputation: 4703

Well, std::move(x); is simply casting to r-value reference - it doesn't do anything. But OK, assume you had this:

int x = 42;
int z = std::move(x);
int y = x; // is this ok?

Yes, it is OK and x, y, z will all be 42. Because for trivial types moving is the same as copying.

But what of other more complex classes?

In general, there are only a few strict requirements for moving and move-from objects.

  1. moved-from object needs be copy/move assignable and destructible.
  2. target should be "equal" to pre-moved source.

These requirements are necessary. A lot of STL functionality and other libraries will not operate properly with types that fail to support these.

In practice, simple POD types simply perform a copy on move while containers transfer resource ownership from source to target while destroying whatever resources target owned. Technically, data swap between the objects is also a legitimate action - and some believe it to be a good idea - I strongly disagree with it because if I wanted to swap data then I'd trigger std::swap instead of std::move.

Nevertheless, there is no strict requirement what move must do to moved-from objects - which is important when dealing with complex classes. For instance, one can write a custom allocator for std::vector that will explicitly forbid to move, in which case on move some sort of data copying mixed with data moving will take place and different versions of STL may or may not clear original object.

Notes: cppreference has explicitly stated requirements on moved-from objects for majority of classes in the documentation. So you'd know what exactly what to expect and it's not always intuitive. Usually they go for the laziest action possible.

Upvotes: 2

Related Questions