title: Deleting objects in callback function
body: <p>I am sending an HTTP request to save/update data on the server. The request is made asynchronously and a callback function is called when it completes. Everything works fine except that sometimes, the application crashes in the callback.</p>
  
  <p>This is what I am doing:</p>
  
  <pre><code>user = new User();
  user-&gt;saveOnServer();
  user-&gt;zombie = true;  // Mark the user that it needs to be deleted in the callback.
  </code></pre>
  
  <p>In <code>User</code>, I have a <code>saveOnServer()</code> method:</p>
  
  <pre><code>void User::saveOnServer(){
      Request *request = new Request();
  
      // Send request to the server and register the callback.
      request -&gt;setCallback(&amp;userCallback, (void*)this);
  }
  </code></pre>
  
  <p>The callback:</p>
  
  <pre><code>void userCallback(void *data){
      User *user = (User*)data;
  
      // Do something here.
      // Delete user if it's a zombie.
      if(user-&gt;zombie)
          delete user;
  }
  </code></pre>
  
  <p>At times, I need to create a new user after sending a request to the server:</p>
  
  <pre><code>user = new User();
  user-&gt;saveOnServer();
  user-&gt;zombie = true;
  // Some code comes here.
  if(user)
      delete user;
  user = new User();
  </code></pre>
  
  <p>The problem is that in such cases, the application crashes when deleting the user in the callback as it has already been deleted. Another issue is that the callback deletes user but <code>user</code> pointer in <code>main</code> is still pointing to some address (dangling pointer) and so I again try to delete it.</p>
  
  <p>I am not sure what is the best way of managing memory in this case. I have <code>zombie</code> in place because there are cases when I do not want the callback to delete the user.</p>