I\'ve tried to code like this several times:
struct Foo
{
double const& f;
Foo(double const& fx) : f(fx)
{
printf(\"%f %f\\n\", f
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 ]