Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an object after std::move doesn't result in a compilation error

Tags:

After std::move is called on an object, why doesn't the language cause a compilation error if the object is used after?

Is it because it is not possible for compiler to detect this condition?

like image 568
Jubin Chheda Avatar asked Mar 14 '17 20:03

Jubin Chheda


People also ask

What happens to object after std move?

Nothing. It'll be treated as any other object after that. This means that the destructor will still be called.

What happens std move?

std::move itself does "nothing" - it has zero side effects. It just signals to the compiler that the programmer doesn't care what happens to that object any more. i.e. it gives permission to other parts of the software to move from the object, but it doesn't require that it be moved.


1 Answers

The general principle in C++ language design is "trust the programmer". Some issues I can think of with rejecting any use of the object after it has been an argument to std::move.

  • To determine whether a given use is after a call to std::move in the general case would be equivalent to solving the halting problem. (In other words, it can't be done.) You would have to come up with some rules that describe what you mean by "after" in a way that can be statically determined.
  • In general, it is perfectly safe to assign to an object that has been an argument to std::move. (A particular class might cause an assertion, but that would be a very odd design.)
  • It's hard for a compiler to tell whether a given function is going to just assign the elements of the class new values.
like image 168
Martin Bonner supports Monica Avatar answered Sep 16 '22 14:09

Martin Bonner supports Monica