Garbage collection and closures.

ANtlord via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 17 11:45:16 PDT 2017


On Saturday, 17 June 2017 at 17:15:50 UTC, Adam D. Ruppe wrote:
> 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.

Thanks a lot, Adam! Everything is clear. Except for the bug. I've 
got an expected result of a value of the variable from #2. The 
value equals to number from sequence plus one in each iteration. 
There are ten iterations.

What's wrong? Are there should be five iterations? It doesn't 
make sense for me due to the variable assigned value from the 
sequence 0..10. Or do I look at the wrong place? Can you give me 
a link to the bug?

Thank you again!


More information about the Digitalmars-d-learn mailing list