Is this a bug or feature?
BCS
ao at pathlink.com
Tue Jan 16 07:56:48 PST 2007
Reply to Kirk,
> Li Jie wrote:
>
[...]
> D does not have true closures. If the stack frame of the enclosing
> function is invalidated, then all bets are off.
>
> In Foo.foo above, the 'value' variable is a member of the 'this'
> reference. When Foo.foo returns, that delegate literal's context
> pointer is invalidated, and (therefore) so is the 'this' reference.
>
> If you want a delegate with a more persistent context, you must use a
> delegate to a member function, as in:
>
> class Foo {
> int value = 3;
> ~this() { writefln("dtor"); }
> void foo() {
> writefln(value);
> }
> }
> void main() {
> // Note the '&'
> void delegate() dg = &(new Foo).foo;
> std.gc.fullCollect();
> dg();
> }
What I would like to see is "scoped" delegate literals. This would let you
make a delegate literal and say what pointer to use for the context.
My choice for a syntax would be allowing delegates as dot operators on object
references and other pointers.
class Foo
{
int value = 3;
int delegate() foo()
{
return this.{return value;};
}
}
More information about the Digitalmars-d-learn
mailing list