Return a local object rvalue reference,right or wrong?
Returning a reference to a local automatic variable is always wrong. The variable will be destroyed when the function returns, so any use of the reference will give undefined behaviour.
It makes no difference whether it's an rvalue or lvalue reference.
When the function return ,local object has been released.
if write code like this:
Widget&& makeWidget()
{
Widget w;
…
return std::move(w);
}
So consider the following three sections of code:
First:
Widget&& w= makeWidget();//w is a dangling reference,variable will be destroyed when the function returns
Second:
void foo(Widget&& w){...}//w is a dangling reference too
foo(makeWidget());
Third:
void foo(Widget w){...}//OK,will copy it
foo(makeWidget());
So answer is wrong.
And Note that:
Rvalue references can be used to extend the lifetime of a modifiable temporary (note, lvalue references to const can extend lifetimes too, but they are not modifiable)
Whenever a reference is bound to a temporary or to a base subobject of a temporary, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:
a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.
a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.
Widget&& makeWidget(){
return Widget(123);//error
}