[comp.lang.c++] C++ Constructor Failing

murphy@photon.mpr.ca (Gail Murphy) (11/01/90)

Is there a way to gracefully fail out of a C++ constructor 
ensuring all memory is tidied up?

For instance, suppose class FOO takes two integer values in
its constructor.  For FOO to be validly defined, integer 1 must
be less than integer 2.  However, at some point, a FOO constructor
is called with integer 2 greater than integer 1.

How can this be caught and handled without exceptions?  Can it?

Gail Murphy                     | Voice : (604) 293-5462
MPR Teltech Ltd. 		| Fax   : (604) 293-5787
8999 Nelson Way, Burnaby, BC    | E-Mail: murphy@eric.mpr.ca
Canada, V5A 4B5                 |         eric.mpr.ca!murphy@uunet.uu.net

jgro@lia (Jeremy Grodberg) (11/06/90)

In article <2415@kiwi.mpr.ca> murphy@eric.mpr.ca (Gail Murphy) writes:
>Is there a way to gracefully fail out of a C++ constructor 
>ensuring all memory is tidied up [without exception handling]?
>

One of the big problems with constructors is that, no, you can't fail
out of a constructor without a generic exception mechanism.  This is
particularly annoying when your constructor tries to allocate memory
on the heap, and you would like to gracefully back out if the allocation
fails.  Until exception handling is implemented (which won't even be in
CFront 3.0, I hear), we are screwed.  

The best official explanation of this I have heard was something like
"constructors are supposed to convert previously allocated memory into
a consistant object; if that object wants to be robust under low memory
conditions, it must be able to exist without being able to allocate
memory on the heap, so it shouldn't matter that the allocation fails in
the constructor.  If the object can't exist properly without memory on
the heap, they you are screwed, because how, other than with generic 
exception handling, could you deal with failure to construct objects on
the stack (automatic variables), compiler generated temporaries, and
objects in the middle of an array of objects?"

Well, I wouldn't really object to this line of reasoning if exception handling
were a reality, and there was a simple way to return Null if the failure
was in fact for an object allocated on the heap.  But, with things the
way they are, I find this more than a little inconvenient.
-- 
Jeremy Grodberg      "I don't feel witty today.  Don't bug me."
jgro@lia.com