Consider the following:
ComplexObject foo()
{
ComplexObject temp;
//Do things with temp
ComplexObject result(temp, SOME_OTHER_SETTING); //1
//Do things with result. Do not use temp at all
return result; //2
}
ComplexObject foo()
{
ComplexObject temp;
//Do things with temp
ComplexObject result(std::move(temp), SOME_OTHER_SETTING); //1
//Do things with result. Do not use temp at all
return std::move(result); //2
}
with the assumption that ComplexObject has a move constructor which is far more efficient than it’s copy constructor.
Is the compiler allowed to effectively transform the first code into the second code, because it knows that ComplexObject cannot be used for the remainder of that block?
Not for
temp, but the compiler can perform other optimizations under the as-if rule, which may have the same effect.For
result, there is a special rule regardingreturnstatements, that will use a move if possible (and elision is preferred over either move or copy).