[gclist] What does a garbage collector do about destructors?

Michael Mounteney gate02@landcroft.co.uk
Sat, 27 Jul 2002 18:29:49 +0100


You may care to insert all or some or none of the following in your GC FAQ, in
the list headed ``There are several ways of handling such situations:'':

``4.  You should also consider whether you should be using destructors if you
are using exceptions to handle OS and other environment errors.
Generalisation number 1:  many objects are for managing resources of one sort
or another:  memory blocks, files, display windows, hardware devices etc.
The traditional practice is to write the resource release code (free the
memory, close the file, destroy the window, unlock the device etc.) in the
destructor and it's an attractive and apparently elegant practice.

``The problem is that almost always the OS release call has an error return
(OK, not C's free()), for which you should be testing and raising an
exception if necessary.  Exceptions in destructors are a very bad thing, as
they make robust handling code almost impossible.  See `box out 1' at the end
of Alan Griffith's frankly brilliant article on
http://www.octopull.demon.co.uk/c++/dragons;  you will probably have to read
the whole article to understand his argument, but that will be an hour very
well spent for all serious programmers, including those that do not care to
touch C++.

``To extend his argument:  if exceptions raised by destructors are a bad
thing, then exceptions raised asynchronously by a garbage collector are
terrible:  the context of the exception will be lost, and the software
basically has the choice between terminating and ignoring the problem.  The
only solution is an explicitly-called finalisation method that releases all
the object's resources.''

--
_______________________________________
Michael Mounteney, technical director.
Mobile 07932 106754.
Landcroft Computing Ltd., 01743 360155.