www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Escaping closure (D1)

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.
Dec 13 2008