Elegant control flow in C++ (or any other language)
<p>I am writing a function which has many return points (depending on what conditions are true) and it does a bunch of <code>new</code>s at different points. At every return point, the set of <code>delete</code>s I need to do are different. And even then, I don't want to do them at different places. What is a good way to handle this? </p>

<p>Some details: Let us consider a function:</p>

<pre><code>int MainClass::testFunction() {
  numThreads++;
  char *a = new char[100];
  // Some computation with a
  if (condition1) {
    numThreads--;
    return -1;
  } 
  char *b = new char[100];
  // Some computation with b
  if (condition2) {
    numThreads--;
    return 42;
  } 
  // Some more stuff. 
  numThreads--;
}
</code></pre>

<p>Now, before <code>return -1</code>, I need to do <code>delete a</code> while before <code>return 42</code>, I need to do <code>delete a; delete b;</code>. And you can imagine how this could get complicated if I had multiple return points. </p>

<p>Here are my solutions:</p>

<p>First solution: Put all deletes at the end of the function, put some labels, store the return value at return points, and use <code>goto</code> (yes, that dirty word!) to jump to appropriate deletes and return after executing those deletes. </p>

<p>In the above example, I could say </p>

<pre><code>superset:
  delete b;
subset:
  delete a;
numThreads--;
</code></pre>

<p>And put <code>goto superset</code> before <code>return 42</code> and <code>goto subset</code> before <code>return -1</code>. </p>

<p>I don't like the solution for obvious reasons! :-)   </p>

<p>Second solution: I can build an inner class instance, and do <code>new</code> on variables of that class instance. Like this...</p>

<pre><code>int MainClass::testFunction() {
  class Local {
    char *a, *b;
    Local () : a(NULL), b(NULL) {}
    ~Local () { if (a != NULL) delete a; if (b != NULL) delete b; }
  };
  Local l = Local();
  l.a = new char[100];
  // Some computation with a
  if (condition1) {
    return -1;
  } 
  l.b = new char[100];
  // Some computation with b
  if (condition2) {
    return 42;
  } 
}
</code></pre>

<p>So, what is the problem? Well, how do I access <code>numThreads</code> variable that was in the method? I want to do <code>numThreads++</code> in the constructor for <code>Local</code> and <code>numThreads--</code> in the dtor of <code>Local</code>. If it helps, <code>testFunction</code> is also a member function of another class. </p>

<p>Thanks for reading. </p>

<p><strong>Update:</strong> Allocating the array on stack is definitely one possibility, but I have run into stack overflow (ah... the name of this website :-)) doing large allocations on stack (stack size for threads is 2MB by default). What I wanted to address in this question was <em>general</em> resource acquisition and destruction. </p>
