On Thursday, 29 March 2018 at 15:16:07 UTC, Ivan Kazmenko wrote:
So, why do delegates of guns[] and huns[] all return 1, and how to correctly reproduce the behavior of funs[] while populating it in a loop?

A delegate is a function with a pointer to the stack frame where it was created. It doesn't copy or insert the value of 'i', it still refers to the very same location in memory as the i from the for-loop. After the for-loop, that value is 1, so all delegates refering to that i return 1. The solution is to generate a new local variable for each closure with a helper function:

```
import std.stdio: writeln;

void main () {
    int delegate () [] funs;
    foreach(i; 0..2) {
        funs ~= constantDelegate(i);
    }

    writeln(funs[0]()); //prints 0
    writeln(funs[1]()); //prints 1
}

auto constantDelegate(int num) {
    return () => num;
}
```

Note that since the delegate leaves the scope of constantDelegate, the stack frame with the value for 'num' will be allocated to the heap because local variables normally don't persist after returning from a function.

Reply via email to