Is it safe to make a const reference member to a temporary variable?

No, this is not safe. More precisely this is UB, means anything is possible.

When you pass 123.0 + 2.0 to the constructor of Foo, a temporary double will be constructed and bound to the parameter fx. The temporary will be destroyed after the full expression (i.e. Foo p(123.0 + 2.0);), then the reference member f will become dangled.

Note that the temporary’s lifetime won’t be extended to the lifetime of the reference member f.

In general, the lifetime of a temporary cannot be further extended by “passing it on”: a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.

And from the standard, [class.base.init]/8

A temporary expression bound to a reference member in a
mem-initializer is ill-formed. [ Example:

struct A {
  A() : v(42) { }   // error
  const int& v;
};

— end example ]

Leave a Comment