What actually happen when I execute this code?
class MyClass
{
MyClass()
{
//do something
delete this;
}
}
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.
}
};