I am using Visual C++ in the Community edition of Visual Studio 2022 with the latest updates. In the C++ code below, main creates an instance of ShowBug and assigns it to the variable sb. The next line creates a 2nd instance of ShowBug and also assigns it to sb.
Before the 2nd line completes, it calls the destructor. But, it does not destruct the first instance, which is what I thought it would do, but instead destructs the newly created 2nd instance. Try it yourself if you find it hard to believe.
So, am I missing something here (i.e. is using the same variable to assign a new instance a bad programming practice?), or is the compiler somehow doing the correct thing? Or, is this a compiler bug?
// ShowBug.h:
using namespace std;
#include <iostream>
#include <string>
class ShowBug
{
// This class is used to show that the destructor seems to be called for the wrong instance.
//
string S;
int *pArray;
public:
inline ShowBug(const string &s) : S(s)
{
}
inline ~ShowBug()
{
std::cout << "Deleting " + S;
}
};
int main()
{
ShowBug sb = ShowBug("First Instance");
sb = ShowBug("Second Instance");
}