Destructor semantics

Joe Greer jgreer at doubletake.com
Thu Aug 12 05:59:31 PDT 2010


"Steven Schveighoffer" <schveiguy at yahoo.com> wrote in
news:op.vhbpkcaieav7ka at localhost.localdomain: 

> 
> Destructors as they are now are too limited, because they cannot be
> sure  they are being called by the GC or not, they must assume so.  So
> in one  sense I agree with you.  But in another sense, we *still* need
> a way to  clean up non-GC resources from GC-allocated items. 
> Preventing GC  allocated items from holding non-GC resources is a step
> in a very wrong  direction.
> 
> I think any one of the proposals here that separates finalizers from  
> destructors should be adequate.  My backwards-compatible one is to
> pass a  parameter to the destructor indicating whether it's being
> called  deterministically or not, but that doesn't lend itself to
> preventing @safe  finalizers.  Michael also has one for using ~~this()
> and ~this().  We  could designate a method that clear uses, like
> dispose() that  deterministically disposes all resources.  I don't
> really like the  interface solution, because looking up an interface
> is expensive, plus  clear is a template so it doesn't need to use
> interfaces. 
> 
> Whatever gets decided, I don't think anything should prevent them from
>  being GC allocated, it's just too limiting for useful code.  The one 
> initiative the compiler could take is to prevent writing a finalizer
> in  @safe code, since that can lead to memory corruption.
> 
> -Steve
> 

Logically speaking if an object isn't destructed, then it lives forever 
and if it continues to hold it's resource, then we have a programming 
error.  The GC is for reclaiming memory, not files.  It can take a long 
time for a GC to reclaim an object and you surely don't want a file 
locked for that long anymore than you want it held open forever.  My 
point is, that it is a programming error to expect the GC be involved in 
reclaiming anything but memory.  IMO, the best use of a finalizer is to 
error out if an object holding a resource hasn't been destructed, because 
there is obviously a programming error here and something has leaked.  
GCs aren't there to support sloppy programming.  They are there to make 
your life easier and safer.

joe


More information about the Digitalmars-d mailing list