I am looking at code of the following form:
class foo
{
public:
foo() {}
//...
};
class bar
{
public:
bar() : ref() {}
private:
const foo &ref;
};
Is initializing a reference using a temporary in this way correct? I know that it is possible to initialize a const reference that's a local variable with a temporary, and that doing so extends the lifetime of the temporary, e.g.
const foo &tmp = funcThatReturnsByValue(); //OK
However, one of the answers to the related initialize reference in initialization list suggests that there is a difference between "short-lived" and "long-lived" references, and that initializing ref
as above is undefined behavior (even though ref
is a const
reference).
12.2.5 in the standard says, in part, "A temporary bound to a reference member in a constructor's ctor-initializer persists until the constructor exits." Is that describing this situation?
This code is ill-formed. You can't default initialize or value initialize a reference.
If you actually had an expression inside of ref()
, then yes, 12.2.5 would apply and the temporary would be destroyed when the constructor exits.
Your example isn't creating a temporary - to do that you need to change to:
bar() : ref(foo()) {}
Now you're binding the reference to a temporary, and that temporary object will be destroyed at the end of the constructor. Your reference will be invalid, and that is Not A Good Thing.
I guess what you want to do is:
bar() : ref(foo()) {}
but don't naively think that the lifetime of a temporary is extended until there's a reference to it. No, it actually is not. So, whether const or not, you sould initialize the reference with a normal object.
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