Possible Duplicate:
Is it safe todelete this?
Okay, I want to use some Object and its delegate ObjectDelegate.
Here is the sample code:
class ObjectDelegate;
class Object {
private:
int a;
ObjectDelegate *delegate;
void crazyMethod();
public:
Object();
~Object();
void setDelegate(ObjectDelegate*);
};
Object::Object() {
delegate = NULL;
a = 9001;
std::cout << "Object Constructor";
}
Object::~Object() {
std::cout << "Object Destructor";
}
void Object::crazyMethod() {
if(delegate != NULL) {
delegate->deleteMe(this);
}
}
//-----
class ObjectDelegate {
public:
virtual void deleteMe(Object*) = 0;
};
//------
class DelegateItself : public ObjectDelegate {
void deleteMe(Object*);
};
void DelegateItself::deleteMe(Object *object) {
delete object;
}
I often use this approach in Objective-C and Java, but how will it work in the C++-from-the-box?
My question is: at the time I running one method in the Object I call from it another method in the another object (DelegateItself) and delete the Object. The stack will be:
- Object::~Object()
- DelegateItself::deleteMe()
- Object::crazyMethod()
So after the destructor method ends deleteMe method also end (after some time). But what will be happen with crazyMethod of non-existing object? If I try to use variable Object::a I will have possibility to get a garbage instead of real value (data will be invalidated) [hope I understood C++ logic]. If I try to call another method in Object I will possibly crash [hope so too]. But will be it guaranteed to end the crazyMethod correctly if there are no subsequent methods will be called?