Re: What risk of undefined behavior if destructor must throw?
On Oct 9, 10:23 am, "Terry G" <tjgol...@netins.net> wrote:
For example, during stack unwinding (the process that
occurs when an exception is thrown) destructors of objects are
called. If one of those destructors throws an exception, the
standard requires that terminate() will be called. So, unless
you like programs that terminate on the spot, a destructor should
not throw an exception if it is being invoked due to an exception
being thrown.
Terminating on the spot seems preferable to ignoring an unanticipated error.
If terminating on the spot is the preferred response to this error,
what is the logic for throwing an exception instead of simply calling
abort()? Throwing an exception may - or may not - terminate the
program. In other words, the program's response to the error will be
just as unknown as the cause of the error itself.
Throwing exceptions from destructors can also cause problems for
the standard library. For example, the standard containers assume
that their elements will not throw when being destroyed (eg
a std::vector<T> assumes that type T's destructor does not throw)
If that assumption is violated then (IIRC) the result is
formally undefined behaviour.
This seems harsh. Shouldn't the STL define (possibly unpleasant) behavior
if a contained object's destructor throws,
so users can decide whether to use the container to hold such "nefarious"
objects.
So, the rule of thumb I get from this is:
If I design a class with a destructor that might throw, make sure it can't
be used in an STL container, i.e uncopyable.
I would go further and make sure such a class could not be used outside
of an STL container either. There is simply no good reason for a
destructor to throw exceptions. After all, the destructor's
implementation cannot know for certain what throwing the exception will
actually do, so it must be the case that whoever wrote the code for the
destructor does not know what they are doing either. And it's hard to
envision why any programmer would willingly choose to entrust their
entire program's ongoing execution on a single class that evidently has
no idea what it is doing.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]