[gclist] Destructor FAQ

David Gadbois gadbois@cyc.com
Thu, 7 Mar 1996 11:13 -0600


There has been a lot of interesting discussion about finalization.
Underlying all the hairy possibilities is a simple question that has
come up a number of times and should go in the FAQ.  Please let me know
if I have missed any juicy examples or ways of dealing with the issue.

Q: What does a garbage collector do about destructors?

A: A destructor is some code that runs when an object is about to be
freed. One of the main uses of destructors is to do manual memory
management.  For example, the destructor for an object may recursively
free the objects it references.  A garbage collector obviates the need
for such uses:  If an object is garbage, all the objects it references
will also be garbage if they are not referenced elsewhere, and so they,
too, will be freed automatically.

There remains the question of what to do with destructors that do
something other than assist in memory management.  There are a
couple of typical uses.

One use is for objects that have state outside the program itself.  The
canonical example is an object that refers to a file.  When a file
object becomes eligible for reclamation, the garbage collector needs to
ensure that buffers are flushed, the file is closed, and resources
associated with the file are returned to the operating system.

Another use is where a program wants to keep a list of objects that are
referenced elsewhere.  The program may want know what objects are in
existence for, say, accounting purposes but does not want the mechanism
of accounting to prevent objects from otherwise being freed.

The are several ways of handling such situations:

1.  In systems where the garbage collector is "built in," it typically
has special knowledge of all the cases where outside resources can be
referenced and can deal with them appropriately.

2.  Many GC systems have a notion of a "weak pointer."  A weak pointer
is one that is not considered as a reference by the garbage collector. 
So if an object is referenced only by weak pointers, it is eligible for
reclamation.  Weak pointers can be used to implement the object list
example.

3.  Many GC systems have a notion of "finalization."  An object may be
registered with the GC system so that when it is about to
reclaim the object, it runs a function on the object that can perform
necessary cleanups.  Finalization is fundamentally tricky.  Some of the
issues are: 1) When does a finalization function run, particularly with
respect to when other finalizers run?; 2) What happens when registered
objects reference each other?; 3) What happens if a finalization
function makes an object not be garbage any more?  There are no pat
answers to these questions.

--David Gadbois