Local variable inside delegate literal

Sergey Gromov snake.scaly at gmail.com
Wed Dec 23 05:46:25 PST 2009


Daniel wrote:
> int delegate()[] funcs;
> funcs.length = 3;
> 
> foreach(i, ref f; funcs)
> {
>   f = int() { return i; }
> }
> 
> foreach(f; funcs)
> {
>   writeln(f());
> }

First, there are syntax errors in your example.  It should be

     f = delegate int() { return i; };

Second, this works in D2:

     foreach(i, ref f; funcs)
     {
       void blah() {
         auto j = i;
         f = delegate int() { return j; };
       }
       blah();
     }

But this doesn't, outputs 2, 2, 2:

     foreach(i, ref f; funcs)
     {
       auto j = i;
       f = delegate int() { return j; };
     }

And this crashes:

     foreach(i, ref f; funcs)
     {
       ({
         auto j = i;
         f = delegate int() { return j; };
       })();
     }

I think these 3 variants should be equivalent.



More information about the Digitalmars-d mailing list