www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Order of destruction of local variables

reply "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm gmx.net> writes:
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?
Mar 28 2014
next sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 03/28/2014 12:03 PM, "Marc Schütz" <schuetzm gmx.net>" wrote:

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

 Is this behaviour guaranteed?
It must be that way because later objects can hold references to earlier objects. Ali
Mar 28 2014
parent "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm gmx.net> writes:
On Friday, 28 March 2014 at 21:10:39 UTC, Ali Çehreli wrote:
 On 03/28/2014 12:03 PM, "Marc Schütz" <schuetzm gmx.net>" wrote:

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

 Is this behaviour guaranteed?
It must be that way because later objects can hold references to earlier objects.
That's actually why I was asking :-) Thanks to both of you!
Mar 29 2014
prev sibling parent "monarch_dodra" <monarchdodra gmail.com> writes:
On Friday, 28 March 2014 at 19:03:22 UTC, Marc Schütz wrote:
 That is, destruction happens in reverse lexical order of 
 declaration, and arrays are destroyed from back to front.

 Is this behaviour guaranteed?
Yes. It's guaranteed by spec.
Mar 28 2014