[Gc] Re: Do finalizers run at exit?
meessen at cppm.in2p3.fr
Thu Dec 27 09:25:45 PST 2007
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.
More information about the Gc