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?