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

1

6

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?

Racon answered 17/5, 2016 at 3:57 Comment(0)
B
5

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.
Baily answered 17/5, 2016 at 4:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.