Is this a bug or feature?

Kirk McDonald kirklin.mcdonald at gmail.com
Tue Jan 16 16:48:13 PST 2007


BCS wrote:
> 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;};
>  }
> }
> 
> 

Method literals, eh? Nifty.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list