[Issue 21929] delegates capture do not respect scoping

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed May 19 03:08:33 UTC 2021


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

Walter Bright <bugzilla at digitalmars.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |bugzilla at digitalmars.com

--- Comment #4 from Walter Bright <bugzilla at digitalmars.com> ---
Let's rewrite it to something that does not use closures:

 int test() @safe {
    int j;
    int*[20] ps;

    for (int i = 0; i < 10; i++) {
        ps[j++] = &i;
    }

    for (int i = 0; i < 10; i++) {
        int index = i;
        ps[j++] = &index;
    }

    int x;
    foreach (p; ps)  {
        x += *p;
    }

    return x;
 }

This code is equivalent in terms of what is happening with references and
scopes.

Compiling it with -dip1000 yields:

  Error: address of variable i assigned to ps with longer lifetime
  Error: address of variable index assigned to ps with longer lifetime

Which is pragmatically what the behavior of the delegate example would be,
because the delegate is also storing a pointer to the variable.

--


More information about the Digitalmars-d-bugs mailing list