Anonymous Delegates

Lutger lutger.blijdestin at gmail.com
Mon Jun 16 05:24:22 PDT 2008


Erik Lechak wrote:
...
> Since delegates have a nice shorthand syntax, they must be more important
> than I realize. Without an associated object, they just sound like
> function pointers to me.
> 
> What am I missing?
> 
> Thanks,
> Erik Lechak

Anonymous delegates do have of sort-of-this pointer: the stack frame.

An example is clearest:

char[] clickedMessage = "you clicked me!";
button.addOnClicked( (Button aux) { 
    Stdout(clickedMessage).newline; 
} ); 

In D1, as long as the scope where clickedMessage lives is valid, the
delegate passed to addOnClicked can access any variable in it. This can
result in weird bugs of course when that scope is no longer valid, but also
makes delegates very fast. In D2 on the other hand, I believe this will
result in a closure, heap-allocating the surrounding stack frame and
storing it with the delegate. Correct me if I'm wrong, I haven't used this
yet.





More information about the Digitalmars-d mailing list