Delegate method to remove self: possible problems?
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/550189/is-it-safe-to-delete-this">Is it safe to <code>delete this</code>?</a>  </p>
</blockquote>



<p>Okay, I want to use some <code>Object</code> and its delegate <code>ObjectDelegate</code>.<br>
Here is the sample code:</p>

<pre class="lang-c++ prettyprint-override"><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 &lt;&lt; "Object Constructor";
}

Object::~Object() {
    std::cout &lt;&lt; "Object Destructor";
}

void Object::crazyMethod() {
    if(delegate != NULL) {
        delegate-&gt;deleteMe(this);
    }
}

//-----

class ObjectDelegate {
public:
    virtual void deleteMe(Object*) = 0;
};

//------

class DelegateItself : public ObjectDelegate {
    void deleteMe(Object*);
};

void DelegateItself::deleteMe(Object *object) {
    delete object;
}
</code></pre>

<p>I often use this approach in Objective-C and Java, but how will it work in the C++-from-the-box?<br>
My question is: at the time I running one method in the <code>Object</code> I call from it another method in the another object (<code>DelegateItself</code>) and delete the <code>Object</code>. The stack will be:</p>

<ul>
<li>Object::~Object()</li>
<li>DelegateItself::deleteMe()</li>
<li>Object::crazyMethod()</li>
</ul>

<p>So after the destructor method ends <code>deleteMe</code> method also end (after some time). But what will be happen with <code>crazyMethod</code> of non-existing object? If I try to use variable <code>Object::a</code> 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 <code>Object</code> I will possibly crash [hope so too]. But will be it <strong>guaranteed</strong> to end the <code>crazyMethod</code> correctly if there are no subsequent methods will be called?</p>
