destructor order
Steven Schveighoffer
schveiguy at yahoo.com
Wed Jan 26 05:48:40 PST 2011
On Wed, 26 Jan 2011 07:55:22 -0500, Albin Breen <abreen at ea.com> 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
More information about the Digitalmars-d
mailing list