auto used as scope

Martin Persenius martin at persenius.net
Wed Apr 18 05:42:23 PDT 2007


Hi!

There is inconsistency in the usage of 'auto', where it actually behaves as 'scope'. According to users of #d this might be because auto comes from scope. I would like to understand why the dtor is and is not called in the following cases, and the reasoning for having it that way.

import std.stdio;

class Foo {
    this() {
        writef("0");
    }

    ~this() {
        writef("1");
    }
}

int main() {
    try {
        scope(failure) writef("4");
        scope(exit) writef("2");
        auto Foo f = new Foo();
        throw new Exception("msg");
        scope(exit) writef("9");
        scope(success) writef("8");
        scope(failure) writef("7");
    }
    catch (Exception e)
        writef("%s", e.toString);

    writefln();

    try {
        scope(failure) writef("4");
        scope(exit) writef("2");
        Foo f = new Foo();
        throw new Exception("msg");
        scope(exit) writef("9");
        scope(success) writef("8");
        scope(failure) writef("7");
    }
    catch (Exception e)
        writef("%s", e.toString);

    writefln();

    try {
        scope(failure) writef("4");
        scope(exit) writef("2");
        auto Foo = new Foo();
        throw new Exception("msg");
        scope(exit) writef("9");
        scope(success) writef("8");
        scope(failure) writef("7");
    }
    catch (Exception e)
        writef("%s", e.toString);

    writefln();

    return 0;
}

Output:
0124msg
024msg
024msg

The spec page for this is here:
http://www.digitalmars.com/d/statement.html#ScopeGuardStatement
"If any auto instances are to be destructed upon the close of the scope, they also are interleaved with the ScopeGuardStatements in the reverse lexical order in which they appear."



More information about the Digitalmars-d mailing list