[Issue 21929] delegates capture do not respect scoping
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Wed May 19 07:23:51 UTC 2021
https://issues.dlang.org/show_bug.cgi?id=21929
--- Comment #6 from deadalnix <deadalnix at gmail.com> ---
(In reply to Walter Bright from comment #4)
> 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.
Except it is not. In D, closures do allocate on heap.
--
More information about the Digitalmars-d-bugs
mailing list