title: C++ Heap allocation and reuse of memory
body: <p>I've got this small snippet:</p>
  
  <pre><code>Action* newAction(Agent&amp; a, ACTION_MODE&amp; m)
  {
    Action *new_action;
    do
    {
      new_action = new Action(a,m);
    }
    while (!state-&gt;addAction(new_action));
    return new_action;
  }
  </code></pre>
  
  <p><code>state-&gt;addAction(Action *a);</code> will return true if *a was added, false if *a not added (checks to see if *a already exists).</p>
  
  <p>Now, I know that goto's are considered evil from lots of people, so, In the above snippet, re-allocating new_action in every loop, without deleting it, isn't that wrong ?</p>
  
  <p>Wouldn't the following snippet be more "sensible" ?</p>
  
  <pre><code>retry :
      Action *new_action = new Action(a,m);
      if (state-&gt;addAction(new_action))
      {
        return new_action;
      }
      else
      {
        delete new_action;
        goto retry;
      }
  </code></pre>
  
  <p>I'm sorry if this seems elementary but it is something I've wondered about for some time now. What is correct, to delete the memory and then re-allocate, or can I re-allocate instantly ?</p>
  
  <p>EDIT:</p>
  
  <p>Would that be better ? </p>
  
  <pre><code>Action* newAction(Agent&amp; a, ACTION_MODE&amp; m)
  {      
    // state will only allow an action to be added if it does not already exist
    Action *new_action = new Action(a,m);
  
    if (!new_action) return 0;
  
    while (!state-&gt;addAction(new_action))
    {
      delete new_action;
      new_action = new Action(a,m);
    }
  
    return new_action;
  }
  </code></pre>
  
  <p>The caller of this function expects a new action which has been already added to state, so therefore deletion must take place in here.</p>