What happened when the 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, this should be T a;instead T a(), and now I get the output:

bb
hello
zz
hello

But I am confused by the result. Why can this program work successfully?

Edited

I do not think my question is repeated. In my code, the constructor calls the destructor until the function completes. However, he called the double destructor explicitly on this issue.

+4
source share
2 answers

This behavior is undefined: you call the destructor on an object that has not yet been completely constructed.

+4
source

delete, , . , .

#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= new T();
    return 0;
}

:

bb
hello
zz
-2

Source: https://habr.com/ru/post/1660773/


All Articles