[Issue 21929] delegates capture do not respect scoping

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Feb 26 05:57:20 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=21929

--- Comment #10 from Walter Bright <bugzilla at digitalmars.com> ---
Replying to comment #1:

The observed behavior is a direct result of lambdas in D not capturing by
value, they capture by reference.

It is also a direct result of loop variables, `i` and `index` although
disappearing at the end of the scope, are recreated in the exact same place.
Hence all the lambda references refer to the same location where each of the
references points to.

The bug here is that the lambda's lifetime, in both loops, exceeds the lifetime
of the variables `i` and `index`.

The error should be emitted when the first lambda, which refers to `i`, is
assigned to dgs[], which has a lifetime longer than `i`. The same goes for the
second lambda and `index`.

Hence, the following simplified code should fail to compile:

    @safe
    void test() {
        int delegate() dg;
        foreach (i; 0 .. 10) {
            dg = () { return i; };
        }
    }

--


More information about the Digitalmars-d-bugs mailing list