Erroneous usage of variable capture in loops
FreeSlave via Digitalmars-d
digitalmars-d at puremagic.com
Fri Jun 2 07:03:31 PDT 2017
As known this code will not work as we may expect:
import std.stdio;
void main(string[] args)
{
void delegate ()[] delegates;
foreach(i; 0..10) {
int j = i;
delegates ~= delegate() {
writeln(j);
};
}
foreach(dlgt; delegates) {
dlgt();
}
}
All delegates will capture the last value of 'j'.
dmd does not complain about such case at all. Once I made this
mistake myself but noticed it thanks to unittesting. Recently I
found similar erroneous code in dlangui (no PR yet). Probably
there are more projects that have the same mistake unnoticed.
May be compiler should produce error or at least generate warning
on this code.
More information about the Digitalmars-d
mailing list