Topic: the new operator and exceptions


Author: smeyers@netcom.com (Scott Meyers)
Date: 1995/04/21
Raw View
I seem to recall that the committee clarified what happens if an exception
is thrown during construction of an object in a new expression, but I don't
remember what the clarification was.  Given this,

  class Complicated { ... };


What do we know about pc if the Complicated ctor throws an exception?  I'd
like to say we know that pc == 0 and operator delete was automatically
invoked on the memory that was allocated by operator new.  If we don't know
that pc == 0, is the behavior of the following well defined?

  void f()
  {
    Complicated *pc = 0;
    try {
      pc = new Complicated;
    }
    catch ( ... ) {
      delete pc;                   // well-defined?
    }

    delete pc;
  }

There should be no memory leak of the memory allocated for the Complicated
object in the code above.  Is there?

Thanks,

Scott