GC: finalization order?!

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 19 06:03:45 PST 2011


On Saturday 19 February 2011 05:54:43 Martin Kinkelin wrote:
> Hi,
> 
> I'm very surprised by the GC finalization order (D 2.051, Windows).
> 
> Minimalistic test:
> ----------
> import std.stdio;
> 
> class Child
> {
>     this()  { writeln("Child.__ctor()"); }
>     ~this() { writeln("Child.__dtor()"); }
> }
> 
> class Parent
> {
>     private Child _child;
>     this()  { writeln("Parent.__ctor()"); _child = new Child(); }
>     ~this() { writeln("Parent.__dtor()"); }
> }
> 
> int main(string[] args)
> {
>     auto parent = new Parent();
>     return 0;
> }
> ----------
> 
> Output:
> ----------
> Parent.__ctor()
> Child.__ctor()
> Child.__dtor()
> Parent.__dtor()
> ----------
> 
> So parent._child gets destructed before parent, although parent
> obviously holds a reference to the Child instance. My problem is that
> I need to access _child in Parent.__dtor(), which therefore doesn't
> work as I expected.
> Is this a bug or really intended behaviour?!
> 
> Thanks in advance,

IIRC, class destructors aren't supposed to reference any references or pointers 
to the heap. They're intended for cleaning up other resources. I don't think 
that there are any guarantees with regards to the order of the destruction of 
objects which are being garbage collected. But I don't mess with destructors 
much, so I'm not all that well versed in the details.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list