What does return obj(value);return? Returns it the newly constructed object or a copy of it?
The reason why I am asking:
Is
return obj(value);
more efficient than
temp = obj(value);
return temp;
?
Follow-up: If so, is it really a difference, or do compilers optimize this away?
Return statement always returns a copy of the argument object with one exception: when the function returns a reference, the reference might be attached to the argument of
returndirectly, in which case no copy is made, of course.For this reason, from the pedantic point of view in your case there’s no way to say what happens, since we don’t know the signature of the function in which your
returnis used. Does it return a reference or not?If we assume that the function returns a non-reference type (and that is probably what you implied), then, again, a copy is returned in both cases. In the second case you also yourself make an extra copy in
tempobject. So, from the abstract point of view, the second variant makes one extra copy and therefore is “slower”. However, C++ language allows rather far-reaching optimizations in cases like that. Read about RVO (return value optimization) and NRVO (named return value optimization). Because of these optimizations it is actually possible that both variants will produce the same code and, obviously, will be equally efficient.In the end it boils down to the code your specific compiler will be able to generate. If you want to know which is faster either time it with your specific compiler and with your specific compiler settings. Or inspect the generated machine code.