Consider the following functions. I'd like answers for C++17.
MyClass&& func() {
return MyClass{};
}
int main() {
MyClass&& myRef = func();
}
Questions:
func()
an xvalue? Why?myRef
a dangling reference? Or, more specifically, why is func()
returning a dangling reference? Wouldn't returning rvalue reference cause temporary materialization, and extend the temporary object's lifetime?func()
is an xvalue because one of the rules of the language is that if a function is declared to have a return type of rvalue reference to object, then an expression consisting of calling that function is an xvalue . (C++17 expr.call/11).
Temporary materialization occurs any time a reference is bound to a prvalue.
The result of the function is myRef
which is initialized by the prvalue func()
. However if we consult the lifetime extension rules in class.temporary/6 it has:
The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
So the temporary object materialized by func()
is destroyed when the return
statement completes, with no extension.