Should destructors be able to tell who called them?

Steven Schveighoffer schveiguy at yahoo.com
Tue Aug 10 12:03:19 PDT 2010


On Tue, 10 Aug 2010 14:51:56 -0400, Sean Kelly <sean at invisibleduck.org>  
wrote:

> Steven Schveighoffer Wrote:
>
>> One of the common problems of destructors is that they cannot assume any
>> of their GC-allocated resources are valid when inside the destrutor.
>
> Just a note.  It's already possible to do this in D2 using an  
> interface.  Here's a thread about it:
>
> http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=89443&header
>
> And some sample code:
>
> import core.runtime;
>
> interface Disposable
> {
>     void dispose();
> }
>
> bool handler( Object o )
> {
>     auto d = cast(Disposable) o;
>
>     if( d !is null )
>     {
>         d.dispose();
>         return false;
>     }
>     return true;
> }
>
> static this()
> {
>     Runtime.collectHandler = &handler;
> }

I don't like the semantics.  If you inherit from Disposable, then dispose  
is the nondeterministic, and ~this() becomes deterministic?  How does that  
work if you inherit from a non-Disposable object?  I guess it doesn't  
hurt, but I like my solution better for two other reasons:

1. you are not doing a dynamic cast (i.e. linear search) on every  
collected object
2. it costs next to nothing to put a bool on the stack.

-Steve


More information about the Digitalmars-d mailing list