Anonymous Delegates

Jason House jason.james.house at gmail.com
Mon Jun 16 12:30:48 PDT 2008


Nick Sabalausky Wrote:
> In D1 and D2, what happens if you do something like this:
> 
> class MyClass
> {
>     int delegate() callback;
> 
>     void registerCallback(int delegate() callback)
>     {
>         this.callback = callback;
>     }
> 
>     void display()
>     {
>         writefln("{0}", callback());
>     }
> }
> 
> void foo()
> {
>     int val;
>     auto c = new MyClass();
> 
>     val = 1;
>     c.registerCallback({ return val; })
> 
>     val = 2;
>     c.display();  // Does this display "1" or "2"?
> }
> 
> In D1 and D2, does that display "1" or "2"?

It will print "2".  The internal context pointer refers to the stack frame from foo.  When the delegate is called, it'll look up val and find the value of 2.  If you want to get the value of 1, you'll need to bind val to the call... or find a way to make capturing a variable by value work for you.  I don't remember if full closures are part of the latest dmd v1 compiler or if it's just dmd v2.


> As long as I'm asking about delegate stuff, something else I've been 
> wondering too: I know this following syntax for calling a function isn't 
> supported, but is there any technical reason preventing it from being 
> possible?:

I believe converting from function to delegate is no problem, but the reverse is.  I believe functions exist for compatibility with C where just a function pointer is passed in.



More information about the Digitalmars-d mailing list