Possible Duplicate:
C++: Delete this?
There is a class Foobar created on heap. I want to exit application when it dies. It must die, when I call die() function. There are some private properties created on heap – I also need to delete them. I wrote that code:
Foobar::Foobar()
{
m_var = new int(1);
}
Foobar::~Foobar()
{
delete m_var;
exit(0);
}
void Foobar::die()
{
delete this;
}
The question is in delete this line. If I call it, will Foobar::~Foobar() be called, or not?
P.S. If there is better solution, suggest it, please.
Assuming the object is allocated dynamically with
new: Yes,delete thiswill cause the destructor to be called. However, you should be very careful with deletingthis. In particular, you need to ensure that no subsequent operations try to access any members of the class.Also, if this is ever done on memory which is not dynamically allocated (i.e. with
new), this leads to undefined behaviour. In fact, this also leads to undefined behaviour if the object was allocated vianew[].See this link for more information:
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.15
Here’s another SO question about it:
Is delete this allowed?