[Gc] Re: Do finalizers run at exit?
axilmar at otenet.gr
Fri Dec 28 08:11:33 PST 2007
O/H Christophe Meessen έγραψε:
> David Jones a écrit :
>> In C++ you can have the
>> destructor for the object call close() automatically, which is a convenience
>> when the object is created on the stack. However, the destructor won't be
>> called for an object allocated on a GC heap and therefore if you allocate the
>> object on the heap you must call close() explicitly.
> The destructor of a heap object will be called by libgc if the object
> derives from the class gc_cleanup.
>> And if you do that, you have no need for finalizers, period. At least I have
>> yet to see a good use of finalizers in a well-designed and correct program.
> Finalizer are required when writing exception safe code. See the book
> "Exceptional C++" of Herb Sutter for a more detailed discussion on this
> issue. The problem boils down to resource leaks caused by exceptions. A
> GC gracefully crush this problem to oblivion. It solves the memory leak
> problem and, by use of finalizers, any other type of resource leaks.
> Considering your close() method example, a user would have to add try
> catch blocks in many places of its code to ensure the object is properly
> closed if something goes wrong. Adding a finalizer calling the close()
> method avoids this. Note well that the sole role of this finalizer is to
> be a kind of safety net to recycle lost resources occuring in
> exceptional circumstances. As you wrote, a user should be required to
> use the close() method so that resource lifetime is properly controlled
> in normal circumstances.
David Jones suggest to allocate these resource-manipulating objects on
the stack, and therefore your program will be exception safe.
But what if your resource-manipulating objects can not be allocated on
the stack? Then you need exception safety, i.e. finalizers need to be
Of course you can always use a helper class which is allocated on the
stack and finalizes the heap-allocated object when it goes out of
scope...but that defeats the purpose of heap allocation, so we go back
to step 1.
More information about the Gc