TDPL: Manual invocation of destructor

Don nospam at nospam.com
Thu Aug 12 11:46:00 PDT 2010


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.

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.



> 
> 
>> I think in time, the GC may be associated with it's own thread, and may  
>> run on a schedule vs. having to wait for a memory allocation to run.  When  
>> this happens, it's more likely you can rely on the GC to free the  
>> resources in a reasonable amount of time.
> 
> I'll believe that only when I see it. Even one of the most advanced GC around, the one in the Sun JVM, doesn't act as deterministically as you say (maybe the G1 now does, I am not sure).
> 
> Instead of a clear() function it can be added to classes and structs an optional standard method (like .clear()) that when called performs the cleaning of the object, frees all resources (but not the RAM used by the object instance), puts references to null, etc. The deallocation of the RAM is fully left to the GC later. An class that defines clear() keeps the extra bit of state to tell apart the living or dead state of the object, plus an extra assert in the class invariant. This is just an idea, probably not too much good :-)
> 
> Bye,
> bearophile


More information about the Digitalmars-d mailing list