Search code examples
c++default-value

What is the lifetime of reference member default initializer in C++?


Please consider this short code example:

#include <iostream>

struct A
{
    A() { std::cout << "A() "; }
    ~A() { std::cout << "~A() "; }
};

struct B { const A &a = A(); };

int main()
{
    B x;
    std::cout << ". ";
    auto y = B();
    std::cout << ". ";
    auto z = B{};
    std::cout << ". ";
}

GCC prints here ( https://gcc.godbolt.org/z/a83bn54qT ):

A() ~A() . A() ~A() . A() . ~A() 

meaning that the lifetime of A-object initializing reference in x and y is short, but in z the lifetime is prolonged till the end of the scope.

Could you please explain why it is so from C++ standard point of view?


Solution

  • Lifetime extension is not guaranteed since the code is ill-formed.

    [class.base.init]/11:

    A temporary expression bound to a reference member from a default member initializer is ill-formed. [Example 8:

    struct A {
      A() = default;        // OK
      A(int v) : v(v) { }   // OK
      const int& v = 42;    // OK
    };
    A a1;                   // error: ill-formed binding of temporary to reference
    A a2(1);                // OK, unfortunately
    

    — end example]