Trouble with anon delegates.
BCS
ao at pathlink.com
Tue Jan 16 14:16:18 PST 2007
Reply to Pragma,
> All,
> I ran into a small problem regarding the use of anon delegates, and
> what their context (.ptr) is set to. If anyone
> can share any insight as to if this is a bug or not, I would
> appreciate it.
> In short: I'm attempting to create delegates on the fly and use them
> elsewhere. After many strange errors, I narrowed it down to the
> following case. Note the assertions at the end:
>
> abstract class Foobar{
> Fn getFn();
> }
> alias void delegate() Fn;
>
> auto foo = new class Foobar{
> int x;
> Fn getFn(){
> return { x = x };
> }
> };
> auto fn = foo.getFn();
> assert((&foo.getFn).ptr is foo); // passes
> assert(fn.ptr is foo); // fails (ptr does *not* point to the object)
> So by this, anon delegates are not the same as actual object
> delegates. Is this a bug, or is this intentional?
>
> "When comparing with nested functions, the function form is analogous
> to static or non-nested functions, and the delegate form is analogous
> to non-static nested functions. In other words, a delegate literal can
> access stack variables in its enclosing function, a function literal
> cannot."
>
> As you can see, the docs are as clear as mud. I suppose a "non-static
> nested function" wouldn't know about the 'this' pointer, nor care -
> but then why encumber it with the 'delegate' keyword?
>
Really, some BIG RED TEXT needs to be added to the doc in few places. This
is one of them. Anon delegates are totally invalid after the function they
are declared within returns. Any statement of the form:
return {...};
is ALWAYS invalid. This has gotten about a dozen people in the last week
or so and, as you said. "the docs are as clear as mud" on this. Anon delegate
in any scope use the current function's frame pointer as the context. Once
the function returns, this more than likely is junk.
More information about the Digitalmars-d-learn
mailing list