The future of lambda delegates
Mikola Lysenko
mclysenk at mtu.edu
Wed Aug 16 15:20:25 PDT 2006
"Walter Bright" <newshound at digitalmars.com> wrote in message
news:ebvl5s$2k03$1 at digitaldaemon.com...
> An ideal solution would be if the compiler could statically detect if a
> nested class reference can 'escape' the stack frame, and only then
> allocate on the heap. Otherwise, the current (very efficient) method of
> just passing a frame pointer would be employed.
>
Well, in general it is not decidable if a given nested function escapes.
Here is a trivial example:
void delegate() func(void delegate() F)
{
F();
return { F(); };
}
This function will only return a delegate when F halts. One conservative
strategy is to simply look for any nested function declarations in the
function's lexical extent. If such a declaration exists, then that function
must be heap allocated. I suspect that this is how C# handles the problem.
Another possibility is to add a special attribute modifier to the
declaration of the initial function. This places the burden of determining
'escapism' on the programmer instead of the compiler, and is probably the
simplest to implement.
Perhaps the most flexible solution would be a combination of both
approaches. By default, any function containing a nested function
declaration gets marked as heap allocated - unless it is declared by the
programmer to be stack-based. For this purpose, we could recycle the
deprecated 'volatile' keyword. Here is an example:
volatile void listBATFiles(char[][] files)
{
foreach(char[] filename; filter(files, (char[] fname) { return
fname[$-3..$] == "BAT"; })
writefln("%s", filename);
}
In this case, we know that the anonymous delegate will never leave the
function's scope, so it could be safely stack allocated. Philosophically,
this fits with D's design. It makes the default behavior safe, while still
allowing the more dangerous behavior when appropriate.
More information about the Digitalmars-d
mailing list