Garbage collection and closures.

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 17 06:13:17 PDT 2017


On Saturday, 17 June 2017 at 13:03:28 UTC, ANtlord wrote:
> Is GC called every iteration of this loop?

No, it will once on scope entry; where the deepest-referenced 
variable that is actually captured is defined. The compiler 
allocates heap space instead of stack space for the locals, then 
runs the function normally using that space.

The current implementation doesn't quite do this - it actually 
will alloc only once, on function entry, even when there's a 
variable inside a loop that is supposed to be independent. This 
is the cause of the commonly-referenced bug with foreach(i; 
whatever) capture(i); all showing the same number.

When that bug is fixed, it is possible to allocate on each 
loop... but your code doesn't anyway, so you're ok.

It will only alloc once. You can prove this with a debugger btw, 
set a breakpoint on `_d_allocmemory`.


More information about the Digitalmars-d-learn mailing list