Is there any way to delete a class from its pointer, or do you just have to have a function in the class that you can call something like:
Code:void CClass::DeleteClass()
{
delete this;
}
Printable View
Is there any way to delete a class from its pointer, or do you just have to have a function in the class that you can call something like:
Code:void CClass::DeleteClass()
{
delete this;
}
The destructor will be called when you call delete on a pointer to a class. For example,
You should avoid kamikaze classes which has 'delete this' somewhere (anywhere) within them. It is easy to free the memory internally from the class while still assuming it is valid outside (and therefore trying to access invalid memory).Code:class A {};
...
A* obj;
delete obj; // Calls ~A()
Thanks, that helps. Now I can not put "kamikaze" classes in my code. I was having problems accessing invalid memory....
In fact, the ONLY thing you should ever call delete on is a pointer to a dynamically allocated object. In general, you need a 1:1 pairing of new and delete, a well as new[] and delete[].
Agreed. The only "good" use of 'delete this' I have seen was for compatibility with an old (large and deeply embedded) library in an otherwise well designed OOP program.