“delete this” in constructor

前端 未结 3 2055
广开言路
广开言路 2020-12-15 04:19

What actually happen when I execute this code?

class MyClass
{
    MyClass()
    {
        //do something
        delete this;   
    }
}
3条回答
  •  生来不讨喜
    2020-12-15 04:36

    The first thing that I want to understand here is WHY do you want to do something like this?

    Constructor is a member function where your object is actually getting constructed and you can delele an object once it is fully constructed, that's why doing somrthing like this -

    class A
    {
    public:
        A()
        {
            delete this;
        }
    
        ~A()
        {
        }
    };
    

    results in an undefined behavior.

    Also, to add to this, if you perform delete this in the destructor, it is also not correct since the object is itself undergoing the destruction and doing delete this in the destructor will again call the destructor.

    class A
    {
    public:
        A()
        {
        }
    
        ~A()
        {
            delete this;   // calls the destructor again. 
        }
    };
    

提交回复
热议问题