Consider the following functions. I'd like answers for C++17.
MyClass&& func() {
return MyClass{};
}
int main() {
MyClass&& myRef = func();
}
Questions:
- Is the expression
func()an xvalue? Why? - Why is
myRefa dangling reference? Or, more specifically, why isfunc()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
myRefwhich is initialized by the prvaluefunc(). However if we consult the lifetime extension rules in class.temporary/6 it has:So the temporary object materialized by
func()is destroyed when thereturnstatement completes, with no extension.