Possible Duplicate:
C++: Delete this?
Object-Oriented Suicide or delete this;
I wonder if the code below is run safely:
#include <iostream>
using namespace std;
class A
{
public:
A() {
cout << "Constructor" << endl;
}
~A() {
cout << "Destructor" << endl;
}
void deleteMe() {
delete this;
cout << "I was deleted" << endl;
}
};
int main()
{
A *a = new A();
a->deleteMe();
cout << "Exit ...";
return 0;
}
Output is:
Constructor
Destructor
I was deleted
Exit ...
and program exit normally, but are there some memory access violents here?
It’s ok to
delete thisin case no one will use the object after that call. And in case the object was allocated on a heap of courseFor example
cocos2d-xgame engine does so. It uses the same memory management scheme asObjective-Cand here is a method of base object:I don’t think it’s a
c++way of managing memory, but it’s possible