I'm aware that it's normally not a good idea to return with std::move
, i.e.
bigObject foo() { bigObject result; /*...*/ return std::move(result); }
instead of simply
bigObject foo() { bigObject result; /*...*/ return result; }
because it gets in the way of return value optimization. But what in the case of a function with multiple different returns, particularly something like
class bar {
bigObject fixed_ret;
bool use_fixed_ret;
void prepare_object(bigObject&);
public:
bigObject foo() {
if(use_fixed_ret)
return fixed_ret;
else{
bigObject result;
prepare_object(result);
return result;
}
}
};
I think normal return value optimization is impossible in such a function, so would it be a good idea to put in
return std::move(result);
here, or should I rather do (IMO uglier, but that's debatable)
bigObject foo() {
bigObject result;
if(use_fixed_ret)
result = fixed_ret;
else{
prepare_object(result);
}
return result;
}
For local variables, there's no need to
std::move
them in thereturn
statement most of the time†, since the language actually demands that this happens automatically:§12.8 [class.copy] p32
† Copy elision is very restricted in where it can be applied (
§12.8/31
). One such restriction is that the type of the source object has to be the same as the cv-unqualified return type of the function when dealing with a return-statement. It's also not applicable for subobjects of local variables that are about to go out of scope.