how to correctly populate an array of dynamic closures?

ag0aep6g anonymous at example.com
Thu Mar 29 15:38:14 UTC 2018


On 03/29/2018 05:16 PM, Ivan Kazmenko wrote:
>      int delegate () [] guns;
>      foreach (i; 0..2) guns ~= () => i;
>      foreach (i; 0..2) writeln (guns[i] ());  // 1 and 1, why?

Because there's only variable `i`. All delegates refer to that same one. 
With `i` being mutable, this could maybe be argued to be acceptable.

>      int delegate () [] huns;
>      foreach (i; 0..2) {
>          immutable int j = i;
>          huns ~= () => j;
>      }
>      foreach (i; 0..2) writeln (huns[i] ());  // 1 and 1, why?

Same here. There's only one `j`. With immutable, this is certainly a 
problem. https://issues.dlang.org/show_bug.cgi?id=2043

Two possible workarounds:

     int delegate () [] iuns;
     foreach (i; 0..2) iuns ~= (j) { return () => j; } (i);
     foreach (i; 0..2) writeln (iuns[i] ());  /* 0 and 1 */

     static struct S
     {
         int i;
         int m() { return i; }
     }
     int delegate () [] juns;
     foreach (i; 0..2) juns ~= &(new S(i)).m;
     foreach (i; 0..2) writeln (juns[i] ());  /* 0 and 1 */


More information about the Digitalmars-d-learn mailing list