A delegate problem, create delegation in loop
Denis Shelomovskij
verylonglogin.reg at gmail.com
Thu Jul 5 01:26:46 PDT 2012
05.07.2012 9:54, lijie пишет:
> Hi,
>
> My test code:
>
> import std.stdio;
> void main() {
> void delegate()[] functions;
> foreach (i; 0 .. 5) {
> functions ~= {
> printf("%d\n", i);
> };
>
> }
> foreach (func; functions) {
> func();
> }
> }
>
>
> output:
> 5
> 5
> 5
> 5
> 5
This program behaves as expected. Just like C# program that will give
the same output:
---
delegate void MyFunc();
class Program
{
static void Main()
{
var funcs = new MyFunc[5];
for (int i = 0; i < funcs.Length; ++i)
funcs[i] = new MyFunc(() => System.Console.WriteLine(i));
foreach (var f in funcs)
f();
}
}
---
because "i" is the same for every iteration. Different situation is for
such C# loop:
---
for (int i = 0; i < funcs.Length; ++i)
{
int t = i;
funcs[i] = new MyFunc(() => System.Console.WriteLine(t));
}
---
where "t" is local for scope. Here C# behaves correctly, but D doesn't.
This D loop
---
foreach(i; 0 .. 5) {
int t = i;
functions ~= { printf("%d\n", t); };
}
---
prints "4" five times. It's Issue 2043:
http://d.puremagic.com/issues/show_bug.cgi?id=2043
I'm not posting workaround here because bearophile already did it.
--
Денис В. Шеломовский
Denis V. Shelomovskij
More information about the Digitalmars-d
mailing list