I was reading the chapter 13 of C++ Primer when I read :
"It is essential to realize that the call to move promises that we do not intend to use [an rvalue] again except to assign to it or to destroy it. After a call to move, we cannot make any assumptions about the value of the moved-from object."
"We can destroy a moved-from object and can assign a new value to it, but we cannot use the value of a moved-from object."
So I wrote this code to see if I can't actually use a rvalue twice :
#include <iostream> int main(int argc, const char * argv[]) { int&& rvalue = 42; int lvalue1 = std::move(rvalue); std::cout << "lvalue1 = " << lvalue1 << std::endl; int lvalue2 = std::move(rvalue); std::cout << "lvalue2 = " << lvalue2 << std::endl; return 0; } But according to the output of this code, C++ Primer is wrong and I can use the value of a moved-from object several times (I built with the C++11 standard) :
lvalue1 = 42 lvalue2 = 42 I don't understand...
intis. There isn't anything to move from it. It would cost more to copy over the 42 and then erase the 42 than it would to just copy the 42 and leave the 42 in place. In the general sense when you move from an object it is placed in a safe but undefined state. And in this case leaving 42 is perfectly safe. But you can't count on this behaviour. Try this with something more complicated likestd::stringand you'll get very different results.std::moveis just a cast, it only enables moving if the type supports it.std::moveexpresses the concept that - this thing is now temporary and I don't care what you (the compiler) do with it. cppreference has a nice quote "...std::move is used to indicate that an object may be "moved from"..." std::movemovedoesn't do anything to the object. But if the object is actually moved from, if the object is a type defined by the standard library you can call any function that has no preconditions. If it's an object that's not from the standard library you can do anything that its type allows; read its documentation.