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.