A friend of mine showed me a program in C++20:
#include <iostream>
struct A
{
A() {std::cout << "A()\n";}
~A() {std::cout << "~A()\n";}
};
struct B
{
const A &a;
};
int main()
{
B x({});
std::cout << "---\n";
B y{{}};
std::cout << "---\n";
B z{A{}};
std::cout << "---\n";
}
In GCC it prints:
A()
~A()
---
A()
---
A()
---
~A()
~A()
https://gcc.godbolt.org/z/ce3M3dPeo
So the lifetime of A
is prolonged in cases y and z.
In Visual Studio the result is different:
A()
~A()
---
A()
---
A()
~A()
---
~A()
So the lifetime of A
is only prolonged in case y.
Could you please explain why the type of braces influences the object lifetime?