The future of lambda delegates
Sean Kelly
sean at f4.ca
Wed Aug 16 15:19:07 PDT 2006
Walter Bright wrote:
> Sean Kelly wrote:
>> The alternative would be to use a separate keyword for these
>> delegates, 'closure' or 'lambda' or some such, but that's potentially
>> confusing, and leaves anonymous delegates in an odd position.
>
> I *really* want to avoid having to do this. It's almost guaranteed that
> it'll be a rich source of bugs.
As an alternative, since it's really how the delegate is used that's at
issue, perhaps the programmer could simply be given a way to manually
"archive" the stack frame used by a delegate if he knows it will need to
be called asynchronously? From the original example:
Button createButton(char[] click_msg)
{
Button b = new Button();
b.mouseClickCallback = { MsgBox(click_msg); };
return b;
}
Let's assume mouseClickCallback is written like so:
void mouseClickCallback( void delegate() dg )
{
clickHandler = dg;
}
Following my suggestion, it would be changed to this:
void mouseClickCallback( void delegate() dg )
{
dg.archive;
clickHandler = dg;
}
The archive routine would check dg's stack frame to see if a heap copy
of the frame exists (assume it's stored as a pointer at this[0]). If
not then memory is allocated, the pointer is set, the frame is copied,
and dg's 'this' pointer is updated to refer to the dynamic frame.
Returning a delegate from a function would just implicitly call this
'archive' routine. This could still cause errors, as a programmer may
forget to call "dg.archive" before storing the delegate, but I think
this is an acceptable risk and is far better than having the compiler
try to "figure out" whether such a dynamic allocation is needed. It
also seems fairly easy to implement compared to the alternatives, and
offering the feature through a property method would eliminate the need
for a new keyword.
Sean
More information about the Digitalmars-d
mailing list