Closure capture loop variables

via Digitalmars-d digitalmars-d at puremagic.com
Sun May 3 05:55:53 PDT 2015


On Saturday, 2 May 2015 at 18:02:34 UTC, Idan Arye wrote:
> On Friday, 1 May 2015 at 21:42:22 UTC, deadalnix wrote:
>> On Friday, 1 May 2015 at 17:51:05 UTC, Walter Bright wrote:
>>> On 4/30/2015 5:55 AM, Vladimir Panteleev wrote:
>>>> I think Freddy's programs are working as designed.
>>>
>>> Yes, they are.
>>>
>>> D closures capture variables by reference. No, we're not 
>>> changing that.
>>
>> The variable is declared in the block, therefore it is a 
>> DIFFERENT variable at every iteration.
>>
>> This or delegate are unable to respect constness/immutability.
>
> Conceptually - I agree. The variables declared in the block are 
> different on each iteration, and I seriously doubt anyone 
> escaping references to them(be it by closure or by direct 
> pointer) means the same variable in all the iterations.
>
> Pragmatically - I'm not sure if this should be changed. This 
> problem only appears when the closure escapes the scope - which 
> from my experience seems to be the less common case. Unless the 
> compiler can accurately tell when a closure escapes it's scope 
> and when it doesn't, doing the correct thing will mean 
> allocating call-stack frames on the heap *for every iteration* 
> when a closure captures variable inside a loop. This can be a 
> big hit on performance in the majority of the cases where it 
> isn't really needed...

It's trivial to check for escaping with a low false-positive 
rate. And even if not - correctness comes before performance.


More information about the Digitalmars-d mailing list