On Wed, 26 Jan 2011 07:55:22 -0500, Albin Breen <[email protected]> wrote:

Hi! I've been trying out D recently but I'm a little confused about the order in which destructors are called:

class A {
        this() { writeln("ctor"); }
        ~this() { writeln("dtor"); }

        static this() { writeln("static ctor"); }
        static ~this() { writeln("static dtor"); }
}

void main() {
        auto a = new A;
}

This will output:
static ctor
ctor
static dtor
dtor

I would have thought that the static destructor should be the last one (in case there are static dependencies). Have I missed something?

dtors are not guaranteed to run in any order.

See here: http://www.digitalmars.com/d/2.0/class.html#destructors

"The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects."

FYI, the runtime calls static ctors when a thread starts (and once at program start for the main thread) and calls static dtors when a thread exits.

If you want a static ctor/dtor to initialize/destroy shared data (or __gshared), use a shared static ctor/dtor.

-Steve

Reply via email to