c++move-semanticsstdmove

What is left in a variable after using std::move on it?


After using std::move in a variable that might be a field in a class like:

class A {
  public:
    vector<string>&& stealVector() {
      return std::move(myVector);
    }
    void recreateMyVector() {
    }
  private:
    vector<string> myVector;        
};

How would I recreate the vector, like a clear one? What is left in myVector after the std::move?


Solution

  • The common mantra is that a variable that has been "moved-from" is in a valid, but unspecified state. That means that it is possible to destroy and to assign to the variable, but nothing else.

    (Stepanov calls this "partially formed", I believe, which is a nice term.)


    To be clear, this isn't a strict rule; rather, it is a guideline on how to think about moving: After you move from something, you shouldn't want to use the original object any more. Any attempt to do something non-trivial with the original object (other than assigning to it or destroying it) should be carefully thought about and justified.

    However, in each particular case, there may be additional operations that make sense on a moved-from object, and it's possible that you may want to take advantage of those. For example: