Garbage collection and closures.

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 17 10:15:50 PDT 2017


On Saturday, 17 June 2017 at 14:19:34 UTC, ANtlord wrote:
> Excuse me, I can't get what does it mean "deepest-referenced". 
> What the deep you mean? The deep of a closure or deep of the 
> function where the variable is defined. Can you give an example 
> code?

Where the variable is defined that is referenced in the closure.

So:

---
void uses(void delegate() dg);

void foo() {
    int a;
    foreach(b; 0 .. 10) {
       uses( () { a++; } ); // #1
       uses( () { b++; } ); // #2
    }
}
---


In that case, #1 would only be allocated once, at the start of 
the foo() function. It only uses `a`, so it doesn't have to 
allocate again after the point a is defined.

But #2 might allocate each time through the loop. (It currently 
doesn't, but this is filed as an open bug because it is supposed 
to.) Since it uses `b` which is defined inside the loop, it will 
have to allocate a new copy for each iteration.

> Is this function called every time when allocation happens in a 
> heap?

Not any allocation, it is just the function the compiler uses 
when it needs to make a closure.


More information about the Digitalmars-d-learn mailing list