mrsiz mrsiz - 24 days ago 8
C++ Question

What happened when a destructor called in the constructor?

I wrote this code as follows:

#include <iostream>

using namespace std;

class T
{
public:
T()
{
cout << "bb\n";
this -> ~T();
cout << "zz" << endl;
}
~T()
{
cout << "hello\n";
};
};



int main()
{
T a;
return 0;
}


Edited

Sorry, it should be
T a;
instead of
T a()
,and now I get the output:

bb
hello
zz
hello


But I'm confused about the result.Why this program can run successfully?

Edited



I don't think my question is duplicate. In my code, the constructor calls the destructor before the function is finished. However, it called twice destructor explicitly in that question.

Answer

This is undefined behaviour: you're calling the destructor on an object which has not yet been fully constructed.