How to write a proper class destructor?

Kevin Bealer kevinbealer at gmail.com
Sun Jan 28 00:58:32 PST 2007


Bradley Smith wrote:
> 
...
> 
> Are you saying that a proper class destructor can't be written without 
> modifying the language?
> 
> 
> Thanks,
>   Bradley
> 
> 
> [2] http://www.digitalmars.com/d/attribute.html#scope

Some cases like closing a socket or a file opened with the unix open(2) 
are not affected, because the file is identified with an integer, which 
is stored in your class -- you can safely close it.

But, even if the object is a heap object, there exists a fairly simple 
way to do this *without* modifying the GC algorithms.  You can delay the 
destruction until the next GC cycle using a global table -- in the 
example below, the Foo object is never deleted until it is removed from 
the global table, which is done from the destructor, *after* the cleanup 
is done.

Notes:
1. Don't do this for a linked list's next pointer or similar, or you 
will only remove one linked list element per GC run.

2. Look out for cycles -- this is essentially a reference counting 
technique, so cyclical data structures will never be claimed.

3. Don't reorder the lines marked A and B, or use a 'delete f' in the 
destructor because those actions are not safe if the GC runs while your 
destructor is running -- this could happen if this object is manually 
deleted or declared with scope, etc.

class Foo {
     // must be called
     cleanup();
}

class Bar {
     static bool[Foo] pity_the_foo;

     Foo f;

     this()
     {
         f = new Foo;
         pity_the_foo[f] = true;
     }

     ~this()
     {
         f.cleanup(); // A
         pity_the_foo.remove(f); // B
         // delete f; -- Don't do this
     }
}

Kevin



More information about the Digitalmars-d-learn mailing list