Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Rvalue Reference and Temporary Materialization

Consider the following functions. I'd like answers for C++17.

MyClass&& func() {
  return MyClass{};
}

int main() {
  MyClass&& myRef = func();
}

Questions:

  1. Is the expression func() an xvalue? Why?
  2. Why is 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?
like image 486
zemageht Avatar asked Mar 04 '26 15:03

zemageht


1 Answers

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.

like image 67
M.M Avatar answered Mar 07 '26 04:03

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!