Visual Studio: user defined constructor changes object lifetime

Viewed 105

Consider the following example:

#include <iostream>

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

struct B
{
    B() {std::cout << "B()\n";}
    ~B() {std::cout << "~B()\n";}
};

template< typename T>
struct cref
{
    const T &t;
};

int main()
{
    cref<A> a{{}};
    std::cout << "---\n";
    cref<B> b{{}};
    std::cout << "---\n";
}

In Visual Studio 2019 16.10.3 it prints

~A()
---
B()
---
~B()

meaning that object A is destructed in the same line where it was constructed, and the object B lifetime is prolonged till the end of main function scope.

The only distinction between classes A and B is the presence of user defined constructor in B. Can it really change the lifetime of the object according to the standard or it is simply a compiler bug?

1 Answers

As far as I can see, the behavior has changed in Visual Studio 2022 (Microsoft (R) C/C++ Optimizing Compiler Version 19.30.30711.2 for x64).

There it correctly prints

---
B()
---
~B()
~A()

same as GCC and Clang, demo: https://gcc.godbolt.org/z/Me8fdEjbG

So it was really a MSVC's bug.

Related