auto classes and finalizers

Sean Kelly sean at f4.ca
Wed Apr 5 14:20:00 PDT 2006


Jarrett Billingsley wrote:
> "Sean Kelly" <sean at f4.ca> wrote in message 
> news:e10pk7$2khb$1 at digitaldaemon.com...
>>     - a type can have a destructor and/or a finalizer
>>     - the destructor is called upon a) explicit delete or b) at end of 
>> scope for auto objects
>>     - the finalizer is called if allocated on the gc heap and the
>>       destructor has not been called
> 
> Would you mind explaining why exactly there needs to be a difference between 
> destructors and finalizers?  I've been following all the arguments about 
> this heap vs. auto classes and dtors vs. finalizers, and I still can't 
> figure out why destructors _can't be the finalizers_.  Do finalizers do 
> something fundamentally different from destructors? 

Since finalizers are called when the GC destroys an object, they are 
very limited in what they can do.  They can't assume any GC managed 
object they have a reference to is valid, etc.  By contrast, destructors 
can make this assumption, because the object is being destroyed 
deterministically.  I think having both may be too confusing to be 
worthwhile, but it would allow for things like this:

     class LinkedList {
         ~this() { // called deterministically
             for( Node n = top; n; ) {
                 Node t = n->next;
                 delete n;
                 n = t;
             }
             finalize();
          }

          void finalize() { // called by GC
              // nodes may have already been destroyed
              // so leave them alone, but special
              // resources could be reclaimed
          }
     }

The argument against finalizers, as Mike mentioned, is that you 
typically want to reclaim such special resources deterministically, so 
letting the GC take care of this 'someday' is of questionable utility.


Sean



More information about the Digitalmars-d mailing list