Closures and loop scope

Timon Gehr timon.gehr at gmx.ch
Tue Jun 4 14:48:32 PDT 2013


On 06/04/2013 11:38 PM, Nick Sabalausky wrote:
> On Tue, 04 Jun 2013 23:24:51 +0200
> Timon Gehr <timon.gehr at gmx.ch> wrote:
>
>> On 06/04/2013 11:03 PM, Nick Sabalausky wrote:
>>> ...
>>>
>>> So when you put the delegate creation in a loop:
>>>
>>>       foreach(a; iota(0..6))
>>>           dg = () => a;
>>>
>>> It *is* expected that you're *not* sticking 0, 1, 2, 3, etc inside
>>> the delegate. That's because you're not evaluating "a" *at all*
>>> here, you're just crerates a delegate that *refers* to "a" itself.
>>> You're just creating the exact same delegate five times. In other
>>> words:
>>>
>>> You're just saying:
>>> Store the following set of instructions into 'dg': "Read the value
>>> of 'a' and then return it."
>>>
>>> You're *not* saying:
>>> Read the value of 'a' and *then* create a delegate that returns that
>>> value.
>>>
>>>
>>
>> 'a' refers to a different location for every loop iteration. This is
>> a language change in 2.063.
>>
>
> foreach(a;0..5)
>      writeln(&a);
>
> For me, that prints the same address five times in both 2.062 and
> 2.063.

It does not matter. The lifetimes of the different a's do not overlap.

> I would argue that's as it should be.
>

That argument would be mistaken. The compiler is free to eg. unroll the 
loop completely and use different addresses.

Behind the scenes, the foreach loop is rewritten to something like:

for(int __a=0;__a<5;__a++){
     int a = __a;
     writeln(&a);
}


More information about the Digitalmars-d mailing list