Reputation: 1528
What will exactly happen if a member function try to do delete this;
, like in the constructor of the following class?
class A
{
public:
A(int);
~A();
int *pi;
}
A::A(int i)
{
delete this;
pi = new int(i);
}
A::~A()
{
delete pi;
}
Upvotes: 22
Views: 13182
Reputation: 206518
This C++ FAQ entry answers this quite nicely, repeating here:
As long as you're careful, it's OK for an object to delete this
.
Here's how I define "careful":
You are violating the #3 by accessing pi
after delete this
Upvotes: 45
Reputation: 1801
You can delete this
, but this assumes that the instance was created with new
and that you don't access any members of the instance any more.
In your example, pretty much the same would happen if you did
class A
{
public:
A(int);
int *pi;
};
A::A(int i)
{
pi = new int(i);
}
int main()
{
A* p = new A(10);
delete p;
p->pi = new int; //bad stuff
//or
A a(20);
delete &a; //bad stuff
a.pi = new int; //more bad stuff
}
And even more bad stuff happens because when you delete this
, the pi
member is unitialized, leading to destructor attempting to delete a dangling pointer.
Upvotes: 1
Reputation: 272487
In general, invoking delete this
from inside a member function is well-defined, if a little risky.
But it's probably a very bad idea to invoke it from the constructor (I don't know if it's well-defined). Why would you ever want to do that?
Upvotes: 1
Reputation: 146910
Bad things. You can delete this;
but it's generally speaking an extremely bad idea, and once it's done, you cannot touch any member variables or member functions.
Upvotes: 3