[Gc] Re: Do finalizers run at exit?

Christophe Meessen meessen at cppm.in2p3.fr
Thu Dec 27 05:46:49 PST 2007


Achilleas Margaritis a écrit :
> And another question: why finalization is good after a collection, but 
> not at program exit? what's the difference? both situations seem the 
> same to me.
The answer to this question was already given. A good program design 
should avoid relying on finalizer call of objects allocated on the heap. 
See Java for a good application of this rule.
Here are a few reasons I thought of:
- no control of finalize call order and time (i.e. problem with cycles)
- in some case, calling finalizers is a waste of time (i.e. program 
termination)
- slows down gc

Suppose you have a circular doubly linked list of objects. How is the GC 
supposed to know what object to finalize first ? It will have to 
randomly pick one. But then to preserve validity of the data structure, 
one would have to add a finalizer so that each object properly remove 
itself from the list. This object detachment is a pure waste of time. It 
is particularly obvious when the data structure is destroyed when the 
program terminates.

Thus the rule of thumb is to design your program so that it doesn't rely 
on finalizer beeing called.
The possibility to call finalizers is there because of the few 
exceptions where it is required to have them : recycle resources 
controlled by the destructed object like a file descriptor. Keep in mind 
that the program can crash and that the situation where no finalizer is 
called is a possible use case.

The usefulness of GC is to me the most obvious when it comes to make our 
code exception safe.  This currently requires a very good mastering and 
understanding of C++. Of course its importance will vary with the type 
of application. If your program is just inverting matrixes or computing 
n'th decimal of PI, this is indeed not relevant. If the program is a 
server supposed to run for months and handling zillions of transactions 
with many object allocations, then making your code exception safe is 
critical and optimizing garbage collection too.

I gave up smart pointers because avoiding cycles requires significant 
attention and some time more complex design than it should. Beside, in 
most case all this thread safe counter increment/decrement polka is a 
waste of cpu resource. Compare the million pointer assignments (i.e. 
iterators) that may occur in one GC cycle.



More information about the Gc mailing list