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.

Reply via email to