Defer in D
Nick Treleaven via Digitalmars-d
digitalmars-d at puremagic.com
Sun Mar 20 09:57:57 PDT 2016
On 20/03/2016 16:18, Bauss wrote:
>>> defer((int i) => writeln(i), i);
>>
>> If it was defer(() => writeln(i)), would that do the same? (Dpaste
>> won't seem to let me edit your example on my tablet).
(or on my laptop)
> No that's not the same, since the reference to i does not change when
> doing:
> defer(() => writeln(i))
>
> However with defer((int i) => writeln(i), i) you pass the value of i to
> the lambda expression which stores the value in a new reference.
>
> The problem with the first one is the value will always be the last
> value of i.
Thanks. So we need the lambda to capture args (below) rather than
capturing i at the callsite:
void opCall(ARGS...)(void delegate(ARGS) call, ARGS args)
{
stack.put(() => call(args));
}
The closure above allocates its copy of args on the heap, instead of the
callsite closure which captures i by reference.
More information about the Digitalmars-d
mailing list