TDPL: Manual invocation of destructor

bearophile bearophileHUGS at lycos.com
Tue Aug 10 10:09:47 PDT 2010


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