Lambda capture by value
Steven Schveighoffer
schveiguy at gmail.com
Mon Feb 24 20:56:36 UTC 2020
On 2/24/20 3:32 PM, H. S. Teoh wrote:
> To fix this, copy the value of 'i' to a local variable inside the loop
> body, then the lambda will correctly capture a unique per-iteration
> instance of the variable. Like this:
>
> foreach (i; iota(5))
> {
> auto _i = i;
> printers[i] = () { write(_i); };
> }
Nope. It doesn't ;) Because actually, _i is reused for the loop iteration.
You are thinking that the capture happens on the delegate creation. In
essence, it just sets a flag to the compiler that the enclosing function
must be placed on the heap.
Adam's method works because the nested call's stack frame is captured
when you return that delegate.
In other words, it looks like this:
void main()
{
static struct __mainStackFrame
{
int i;
int _i;
}
__mainStackFrame *frame = new __mainStackFrame; // here's where the
capture happens
with(*frame)
{
// main's function body, with all variables already being declared
}
}
-Steve
More information about the Digitalmars-d-learn
mailing list