12.8 Copying and moving class objects [class.copy] §31 and §32 say:
in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
Hence we can write:
unique_ptr<int> make_answer()
{
unique_ptr<int> result(new int(42));
return result; // lvalue is implicitly treated as rvalue
}
However, I noticed that g++ 4.6.3 also accepts lvalues that are not names, for example:
return (result);
return *&result;
return true ? result : result;
By contrast, return rand() ? result : result; does not work. Is the compiler’s optimizer interfering with the language semantics? As I interpret the standard, return (result); should not compile, because (result) is not a name, but a parenthesized expression. Am I right or wrong?
Regarding parenthesized expressions [√]
You are wrong when talking about parenthesized expressions and that it shouldn’t be able to trigger a move when being returned and containing only the name of a moveable object.
Regarding the constexpr conditional operator [╳]
The way I interpret the standard in regards to constant-expressions and he coditional operator is that the use ofreturn true ? result : resultis well-behaved since it is a constant expression and therefore equivalent to return result;I have now gone through the standard more carefully and nowhere does it say that a constant conditional-expression is the same as if only the "returned" expression would have been written.
Regarding return *&result; [╳]
In C99 it is explicitly stated that
*&resultis the exact equivalent of having writtenresultinstead, this is not the case in the C++ specification.Though we can all agree on that using
*&resultwill indeed yield the same lvalue asresult, but according to the standard*&result(of course) isn’t an expression where "the expression is the name of a non-volatile automatic object".Sure, the expression contains an appropriate name, but it’s not just only that.
To sum things up…