Problem with delegates

Frank Benoit keinfarbton at googlemail.com
Sun Sep 7 07:10:33 PDT 2008


Zarathustra schrieb:
> I know it works with additional function like 'Comparator'.
> Probably when I try use anonymous delegate it have not acces to this, because body of anonymous delegate must be nested inside for example constructor.
> 
> private class
> Drawable{
>   abstract real Comparator();
>   [...]
> }
> public class
> Point{
>   [...]
>   Comparator(){ return this.z; }
>   [...]
> }
> 
> Maybe I will find out another way to do this.
> 
> 
> Frank Benoit Wrote:
> 
>> I haven't tried this, but i think it can work like this:
>> // in Point
>>    // ctors
>>    this(uint o_x, uint o_y, uint o_z){
>>      super( &comparator );
>>      this.x = o_x;
>>      this.y = o_y;
>>      this.z = o_z;
>>    }
>>    real comparator(){ return cast(real)this.z; }
>>
> 

I think this is a D1-only problem. An nested function has always a
reference to the current stack frame and navigates relative to it. In
your case the stack frame of the ctor. If the ctor is completed, the
stackframe gets invalid and a later call to the nested function fails.

In D2, taking the address of the nested function would force the stack
frame to be allocated on the heap and the later call would not make
problems.



More information about the Digitalmars-d-learn mailing list