Order of destruction when garbage collection kicks in

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 9 13:46:12 PDT 2013


On Tue, 09 Apr 2013 15:55:09 -0400, Henning Pohl <henning at still-hidden.de>  
wrote:

> In fact there is no order of destruction. And this is one of the most  
> annoying D problems I recently had to deal with. Look at this example:  
> http://dpaste.dzfl.pl/f3f860b0. This time, it segfaulted. Next time it  
> may (in theory) not, because the dtor of a is called before the one of  
> b. A holds a reference to a B. In the destructor of A I expect b either  
> to be null or a valid instance of B (which has not been destroyed yet).  
> You get a kind of undefined behavior instead. This is IMO a huge  
> drawback towards reference counting with strong/weak references.
>
> Is there right now any way to arrange things?

No.  You are not allowed to access any GC-managed resources inside a  
destructor.

And it won't be null, because that would be extremely costly.  Consider if  
300 objects had a pointer to a block of memory.  Now those 300 objects all  
go away.  By your expectation, if the targeted block of memory was  
collected, the GC would have to spend time going through all those 300  
pointers, setting them to null.  When they are about to all be destroyed.   
99.99% of the time, that would be wasted, as those 300 objects may not  
even have destructors that care.

A destructor is ONLY for destroying non-GC managed resources, nothing  
else.  Like an OS file handle for instance.

-Steve


More information about the Digitalmars-d mailing list