Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the lifetime of a C++ temporary object created in ?: expression extended by binding it to a local const reference?

It is not clear to me whether the lifetime of a temporary object would be extended by binding it to a const reference in a ?: expression:

class Foo {...};

Foo *someLValue = ...;

const Foo& = someLValue ? *someLValue : Foo();

Is the lifetime of the temporary created by calling the default constructor Foo() extended by binding it to the local const ref even though the binding is conditional? Or does this create a dangling reference because the temporary value of Foo() would be destroyed at the end of the ?: expression?

like image 999
Palo Avatar asked May 17 '16 03:05

Palo


1 Answers

In this code, the second and third operand of the conditional operator have different value categories (lvalue and prvalue).

That means that the result of the conditional operator is a prvalue of type Foo, which denotes a temporary object copy-initialized from the selected operand.

The reference binds directly to this temporary object and so the temporary's lifetime is extended.

Notes:

  • The reference never binds directly to *someLValue, nor even to Foo().
  • The temporary being initialized from Foo() is a copy elision context so you may not be able to observe the temporary in this case.
  • The temporary is non-const even though the reference is to const.
like image 152
M.M Avatar answered Oct 31 '22 23:10

M.M