www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - PONDER: Maybe destructors should be "last chance functions"

I was in the shower today, thinking about parsers, and I thought to 
myself, "when the parser at layer X becomes garbage, I want it to notify 
layer X+1 about it, and report a syntax error."

The problem is, if layer X+1 is also a garbage collected object, and if 
all of the references to X+1 are indirectly from layer X, then this 
won't work.  The reason is that objects are considered garbage and 
*then* their destructors are run...which means that a garbage object 
can't assume that things it points to are still valid.

What if, instead of destructors, we had "last chance" functions, which 
the GC called when it thought that an object was about to be garbage? 
The called object could assume that all of the things that it pointed to 
were still valid.  Also, there is the potential to "save" an object by 
storing a reference to it in some live object.  Object that were saved 
at the last moment would not become garbage.  (This means, of course, 
that your "last chance function" could run arbitrarily many times.)

Of course, the semantics of "save" are a little questionable...do we run 
a whole 2nd GC pass?  Preferably not.  I'm still working on that part of 
it.  I haven't yet come up with a better idea than explicitly tell the 
GC "save me".  It's a hack, and leaves space for memory leaks.

Here's an example of using a last chance func to handle weak references:

   struct StrongRef(T)
     T  *val;
     T **weak;

       // set the weak pointer to null, so users of it will realize that
       // it's no longer valid
       *weak = null;

   StrongRef!(T) opCall(T *val)
     StrongRef!(T) ret;
        ret.val  = val;
        ret.weak = new T*;
       *ret.weak = val;
     return ret;
Mar 21 2008