how to correctly populate an array of dynamic closures?

ag0aep6g anonymous at example.com
Thu Mar 29 22:09:10 UTC 2018


On Thursday, 29 March 2018 at 20:26:59 UTC, kdevel wrote:
> What is the lifetime of the first loop's variable i?

It lives as long as the delegate.

> What about this example:
>
> ``` bug2.d
> import std.stdio;
>
> void main ()
> {
>    int delegate () [] dg;
>    foreach (i; 0..2) {
>       int *j;
>       if (i == 0) {
>          auto k = i;
>          j = &k;
>       }
>       else {
>          auto l = i;
>          j = &l;
>       }
>       dg ~= () => *j;
>    }
>    foreach (p; dg)
>       p ().writeln;
> }
> ```

As far as I can understand it, you get a closure for j, but not 
for i, k, or l. So `*j` will be garbage.

The compiler doesn't consider where j points. It just goes by the 
variables that are used in the delegate.


More information about the Digitalmars-d-learn mailing list