[Issue 2043] Closure outer variables in nested blocks are not allocated/instantiated correctly: should have multiple instances but only have one.

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Fri Oct 3 04:38:16 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=2043

--- Comment #19 from Artem Borisovskiy <kolos80 at bk.ru> ---
> If the loop index is mutable, then I think
> it's OK to make it shared across loop iterations.
Ridiculous.

----------------------------------
void delegate()[] dgList;
const count = 10;

// 1
for (int i = 0; i < count; ++i)
  dgList ~= { writeln(i); }

// 2
foreach (immutable i; iota(count))
  dgList ~= { writeln(i); }
----------------------------------

Why should 1 and 2 behave differently? Lambdas should capture outer variables
in a consistent way - by copying them to their activation record, just as all
other languages do. If you really want to capture the counter itself, you
should use a pointer, although it doesn't make sense either, because you'll get
an address of a stack-allocated variable.

--


More information about the Digitalmars-d-bugs mailing list