Thread overview
Order of destruction of local variables
Mar 28, 2014
Marc Schütz
Mar 28, 2014
Ali Çehreli
Mar 29, 2014
Marc Schütz
Mar 28, 2014
monarch_dodra
March 28, 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?
March 28, 2014
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

March 28, 2014
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.
March 29, 2014
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!