Topic: Exceptions, constructors, and new
Author: jbn@lulea.trab.se (Johan Bengtsson)
Date: 1 Apr 93 15:53:58 GMT Raw View
Timothy Writer (twriter@rd.hydro.on.ca) wrote:
: What is the correct way to handle exceptions thrown by constructors
: during construction of an object on the heap? For example, consider the
: following code fragment:
: Foo *foo = new Foo;
: What should I do if Foo::Foo() throws an exception? As I understand it,
: the memory for a Foo is allocated by new before Foo::Foo() is invoked.
: When an exception is thrown, this memory is not released.
Sounds like a compiler bug to me. A good implementation should
IMHO regard the allocated raw memory obtained from operator new()
as an anonymous object with a pseudo-destructor that deallocates
the memory. The compiler should arrange for this (inline) destructor
to be called if an exception occurs during the call to Foo::Foo(),
just like it calls other destructors during the exception cleanup
phase.
Perhaps this is something that should be explictly specified by
the standard (is it?)?
BTW, there is no easy way for you to know if the exception occured
while allocating memory (rare, but possible), or in Foo::Foo().
You should probably keep track of dynamically allocated objects
by using "handle" classes that manages a heap object each.
That way you don't have to worry about who calls "delete foo",
in case an error occurs later on.
"The C++ Programming Language 2nd Ed", pp309-311, should give you a
hint or two (see the MemPtr template).
--
-------------------------------------------------------------------------
| Johan Bengtsson, Telia Research AB, Aurorum 6, S-977 75 Lulea, Sweden |
| Johan.Bengtsson@lulea.trab.se; Voice:(+46)92075471; Fax:(+46)92075490 |
-------------------------------------------------------------------------