Catching a memory allocation error in a constructor?
<p>I sometimes need a class in C++ which allocates dynamic memory. Since this can fail, I need to detect when the memory cannot be allocated. Usually, I do this as in the example below, ie. I do not allocate memory in the constructor but have a separate method for this, where a <code>bad_alloc</code> exception can be caught.</p>

<p>Is there any way to allocate memory in the constructor and catch an exception?</p>

<pre><code>try {
  my_class my_instance;
}
catch ...
</code></pre>

<p>does not work because the scope of <code>my_instance</code> is limited to the <code>try</code> block.</p>

<p>Here is a minimal example:</p>

<pre><code>#include &lt;iostream&gt;

class my_class {
private:
  char * data;

public:
  my_class () {
    data = NULL;
  }

  ~my_class () {
    delete [] data;
  }

  void init () {
    data = new char [10000000000];
  }

  void write (int x) {
    data[x] = 1;
  }
};

int main() {
  my_class my_instance;
  try {
    my_instance.init();
  }
  catch (std::bad_alloc&amp;) {
    std::cout &lt;&lt; "Memory overflow.\n";
    return 1;
  }

  my_instance.write(10);

  std::cout &lt;&lt; "OK.\n";
  return 0;
}
</code></pre>
