mrsiz
mrsiz

Reputation: 193

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.

Upvotes: 4

Views: 274

Answers (2)

hrishi
hrishi

Reputation: 433

When you call a destructor inside a constructor and you don't delete the dynamically generated memory explicitly using delete statement then it gonna work just like a normal function call. For the reference I have made the appropriate changes in the code so that destructor behaves normal.

#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;
}

output :

bb
hello
zz

Upvotes: -2

Smeeheey
Smeeheey

Reputation: 10336

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

Upvotes: 4

Related Questions