Destructor semantics

Steven Schveighoffer schveiguy at yahoo.com
Thu Aug 12 06:18:09 PDT 2010


On Thu, 12 Aug 2010 08:59:31 -0400, Joe Greer <jgreer at doubletake.com>  
wrote:

> "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.

An open file maybe, but why should the compiler decide the severity of not  
closing the resource?  What if the resource is just some C-malloc'd memory?

Note, you are free to write your finalizer to do exactly what you want  
(print some error if it's called and the file's still open).  I just don't  
think the compiler should be involved in the decision, because it's too  
ill-equipped to make one.

-Steve


More information about the Digitalmars-d mailing list