TDPL: Manual invocation of destructor

Steven Schveighoffer schveiguy at yahoo.com
Thu Aug 12 11:56:36 PDT 2010


On Thu, 12 Aug 2010 14:46:00 -0400, Don <nospam at nospam.com> wrote:

> bearophile wrote:
>> Steven Schveighoffer:
>>
>>> By clearing that resource in the destructor, and allowing a way to   
>>> manually call that destructor, the class works in all three  
>>> situations:   manual resource management (via clear), scoped  
>>> destruction, and GC  destruction.
>>  From what I have seen so far:
>> 1) the semantics of clear() is a mess
>> 2) objects don't get deallocated deterministically when they go out of  
>> scope
>> 3) and the GC is not deterministic, you can only partially hope your  
>> destructor will be called at program end, in some random order. And  
>> sometimes your object destructors will not be called even at the end of  
>> the program.
>>  The only thing I see good here is to use a scope(exit) to close the  
>> file:
>> auto f = new File(...);
>> scope(exit) f.close();
>> ...
>>  While clear, scoped destruction of the object, and GC destruction  
>> don't seem enough in this situation, or any other situation where there  
>> you have a resource that is not RAM.
>
> I completely agree. Everything I've read about finalizers indicates that  
> it's a completely broken concept. It seems as though it was initially  
> envisioned (in Java, in the early documents of C#, etc) as equivalent to  
> destructors. Apparently it took some time to realize that the value in  
> destructors comes almost entirely from the deterministic lifetime.
> Instead, finalizers seem to be equivalent to registering a callback with  
> the runtime.

No, it's purpose is to be a last-ditch effort to clean up unmanaged  
resources.  It's kind of like a safety net.

Essentially, if you are relying on the GC to destroy your object, and you  
haven't cleaned up all the resources in that object, you don't want those  
resources to leak.  Once the object is destroyed, the resource is leaked  
if it's not cleaned up.  Is allowing the destructor to clean up your  
resource a program error?  It's up to the developer to decide that.

D still lacks a standard way of deterministic destruction.  Clear doesn't  
work because it still calls the destructor, and the destructor must assume  
it's non-deterministic.

> Their main legitimate use seems to be for contract programming (though  
> I've never heard it described in that way): at the moment of garbage  
> collection, check that the destructor has actually been run.

It can be set up this way, just throw an exception if the resource isn't  
cleaned up instead of silently cleaning up the mess in your destructor.

-Steve


More information about the Digitalmars-d mailing list