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?
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:
*someLValue
, nor even to Foo()
.Foo()
is a copy elision context so you may not be able to observe the temporary in this case.const
even though the reference is to const
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With