Trouble with anon delegates.
Pragma
ericanderton at yahoo.removeme.com
Tue Jan 16 13:53:59 PST 2007
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?
--
- EricAnderton at yahoo
More information about the Digitalmars-d-learn
mailing list