how to correctly populate an array of dynamic closures?

ag0aep6g anonymous at example.com
Thu Mar 29 20:05:35 UTC 2018


On Thursday, 29 March 2018 at 19:02:51 UTC, kdevel wrote:
> On Thursday, 29 March 2018 at 15:16:07 UTC, Ivan Kazmenko wrote:
[...]
>> 	int delegate () [] guns;
>> 	foreach (i; 0..2) guns ~= () => i;
>> 	foreach (i; 0..2) writeln (guns[i] ());  // 1 and 1, why?
>
> Isn't this undefined behavior? The first loop variable named 
> "i" already went out of scope when the delegate is invoked.

Not undefined behavior. At least, not for that reason.

The compiler sees that the delegate references `i`. So it puts 
`i` on the heap where it survives beyond the `foreach` scope. 
That's a closure.

https://dlang.org/spec/function.html#closures


More information about the Digitalmars-d-learn mailing list