delegate confusion
bitwise via Digitalmars-d
digitalmars-d at puremagic.com
Fri Aug 4 11:23:44 PDT 2017
On Friday, 4 August 2017 at 17:18:41 UTC, Steven Schveighoffer
wrote:
> On 8/4/17 12:57 PM, bitwise wrote:
>> [...]
>
> Because the stack frame of foo or bar or baz is stored on the
> heap BEFORE the function is entered. The compiler determines
> that the stack frame will need to be captured, so it captures
> it on function entry, not when the delegate is taken. Then the
> variable location is reused for the loop, and all delegates
> point at the same stack frame.
>
> This is necessary for cases where the delegate may affect the
> frame data during the function call. For instance:
>
> void foo()
> {
> int i;
> auto dg = { ++i;};
> dg();
> dg();
> assert(i == 2);
> }
>
> What is needed is to allocate one frame per scope, and have the
> delegate point at the right ones.
>
> Note, the C++ behavior uses dangling stack pointers, and not
> something we want to support in D.
>
> -Steve
Thanks for clearing this up. Looking over my examples again, this
makes sense now. I suppose while this behavior is not ideal, it
does mean that I can safely throw lambdas that capture things
into a queue to be executed later, which was my main concern.
I wish this forum was a little more advanced so I could change
the post title I fudged and make this information more visible =/
More information about the Digitalmars-d
mailing list