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

前端 未结 6 1838
太阳男子
太阳男子 2021-01-13 09:32

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         


        
6条回答
  •  一生所求
    2021-01-13 09:59

    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 ]

提交回复
热议问题