Can we fix this?
jfondren
julian.fondren at gmail.com
Wed Sep 29 14:16:50 UTC 2021
On Wednesday, 29 September 2021 at 10:44:53 UTC, Imperatorn wrote:
> https://issues.dlang.org/show_bug.cgi?id=2043
>
> Impossible?
... Documentation:
D has two kinds of blocks, the `{ ... }` kind and the `(){ ...
}();` kind. Within the former, for efficiency, [something about
this bug]. Within the latter, closure environments will be as
expected from other languages at the cost of additional
allocation. These "bubble blocks" are admittedly ugly but this is
part of D's firm stand against the programming practices of the
Scheme community.
```d
void delegate()[] dgList;
void main() {
import std.stdio : writeln;
foreach(int i; [1, 2, 3]) {
auto b = i+2;
dgList ~= { writeln(b); };
writeln(&b); // b will be the *same* on each iteration
}
foreach (dg; dgList)
dg(); // output: 5 5 5
}
```
vs.
```d
void delegate()[] dgList;
void main() {
import std.stdio : writeln;
foreach(int i; [1, 2, 3]) (){
auto b = i+2;
dgList ~= { writeln(b); };
writeln(&b); // b will be *unique* on each iteration
}();
foreach (dg; dgList)
dg(); // output: 3 4 5
}
```
More information about the Digitalmars-d
mailing list