Order of destruction of local variables

Marc Schütz" <schuetzm at gmx.net> Marc Schütz" <schuetzm at gmx.net>
Fri Mar 28 12:03:20 PDT 2014


struct MyStruct {
     string name;
     ~this() {
         import std.stdio;
         writeln("destroying ", name);
     }
}

void main() {
     auto a = MyStruct("a"), b = MyStruct("b");
     {
         auto e = MyStruct("scoped e");
     }
     auto c = MyStruct("c");
     MyStruct[3] f = [MyStruct("1"), MyStruct("2"), MyStruct("3")];
     return;
     auto d = MyStruct("d");
}

With current DMD, this outputs:

destroying scoped e
destroying 3
destroying 2
destroying 1
destroying c
destroying b
destroying a

That is, destruction happens in reverse lexical order of 
declaration, and arrays are destroyed from back to front.

Is this behaviour guaranteed?


More information about the Digitalmars-d-learn mailing list