As far as I understand one of the purposes of adding move semantics is to optimize code by calling special constructor for copying \"temporary\" objects. For example, in th
After some digging I find this excellent example of optimization with rvalue references inStroustrup's FAQ .
Yes, swap function:
template<class T>
void swap(T& a, T& b) // "perfect swap" (almost)
{
T tmp = move(a); // could invalidate a
a = move(b); // could invalidate b
b = move(tmp); // could invalidate tmp
}
This will generate optimized code for any kind of types (assuming, that it have move constructor).
Edit: Also RVO can't optimize something like this(at least on my compiler):
stuff func(const stuff& st)
{
if(st.x>0)
{
stuff ret(2*st.x);
return ret;
}
else
{
stuff ret2(-2*st.x);
return ret2;
}
}
This function always calls copy constructor (checked with VC++). And if our class can be moved faster, than with move constructor we will have optimization.
There are many places some of which are mentioned in other answers.
One big one is that when resizing a std::vector
it will move move-aware objects from the old memory location to the new one rather than copy and destroy the original.
Additionally rvalue references allow the concept of movable types, this is a semantic difference and not just an optimization. unique_ptr
wasn't possible in C++03 which is why we had the abomination of auto_ptr.