Please consider this short code example:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
struct B { const A &a; };
struct C { const A &a = {}; };
int main()
{
B b({});
std::cout << ". ";
C c({});
std::cout << ". ";
}
GCC prints here ( https://gcc.godbolt.org/z/czWrq8G5j )
A() ~A() . A() . ~A()
meaning that the lifetime of A
-object initializing reference in b
is short, but in c
the lifetime is prolonged till the end of the scope.
The only difference between structs B
and C
is in default member initializer, which is unused in main(), still the behavior is distinct. Could you please explain why?
()
), that clang doesn't support yet, see compiler_support (Parenthesized initialization of aggregates). – Sochor{}
gives different result. – Sochor