1

Possible Duplicate:
What constitutes a valid state for a “moved from” object in C++11?

Consider something like this:

class Foo {};  
std::vector<Foo> v( 5 );

Is it legal to do something like:

v.front() = std::move( v.back() );  

provided that I do something like this afterwards:

v.pop_back();  

More precisely I want to know what is required for an xvalue that has undergone std::move() semantics.
I know it needs to be destructible (obviously). But anything else? Suppose I would call std::vector::insert() or some other function, that may do some copying/moving of the std::move()ed value behind the scenes.
Is that still legal?

In my real case I have std::vector<std::vector<Foo>> and do stuff with that.
But I don't know if it is legal to std::move() from a std::vector that is still used by the outer std::vector.

Community
  • 1
  • 1
iolo
  • 1,090
  • 1
  • 9
  • 20

1 Answers1

2

Yes, this is valid: you can always destroy a moved-from object. (I cannot find where--or whether--this is specified in the C++ language standard, but if a moved-from object could not be destroyed, I'm sure we'd all consider that a bug.) Since your code only destroys the moved-from object, your code is fine.

The Standard Library imposes additional requirements on the state of a moved-from object and any type with which a Standard Library component is instantiated must follow these additional rules. The gist is that move and copy operations that are valid on non-moved-from objects of a type must also be valid for moved-from objects of the type. So, for example, after moving the last element, you could assign that element a new value: v.back() = Foo();.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Ok! Thank you :) Though I'd love to find that somewhere eithin the depths of the standard I believe you. It is what common sense should tell ;) – iolo Aug 25 '12 at 18:30
  • 1
    @iolo, See 17.3.26 [defns.valid] and 17.6.5.15 [lib.types.movedfrom] – Jonathan Wakely Aug 26 '12 at 10:59