Escaping closure (D1)

Denis Koroskin 2korden at gmail.com
Sat Dec 13 11:07:28 PST 2008


Everyone understands that the following code is incorrect in D1:

int delegate() foo(int x)
{
    int n = x;
    auto bar = () { return n; };

    // do stuff

    return bar;
}

Unfortunately, DMD doesn't detect this kind of errors at compile time, and the spec is not subject to change, so let's make it a runtime error instead!

It is possible to do by making delegate reference counted in debug mode:

int delegate() foo(int x)
{
    int n = x;

    int __bar_referenceCounter = 0;
    auto bar = () { return n; };
    scope (exit) assert(__bar_referenceCounter == 0, bar.stringof ~ " has escaped the scope!");

    // do stuff

    return bar;
} // we get an assertion failure at this point

It is not a breaking change, but will help avoid errors at early stage.



More information about the Digitalmars-d mailing list