Dynamic closure vs static closure
Steven Schveighoffer
schveiguy at yahoo.com
Sun Oct 26 08:39:40 PDT 2008
"Frank Benoit" wrote
> It is great to hear that this issue is getting solved.
> How will be the now syntax?
>
> I wonder if the distinction between dynamic/static closure shall be done
> on the calling site, or the called site.
>
> void foo( void delegate() dg ){
> }
> // -or-
> void foo2( void delegate() dg ){
> }
>
> void bar(){
> int i;
> foo({
> i++;
> });
> // -or-
> foo( scope {
> i++;
> });
> }
>
> Because I think, the foo method/function signature has to define if the
> delegate is escaping or not. The caller might not know it.
>
> If the signature defines this, the compiler can check that and give more
> safety.
I think possibly, there cannot be enforcement of this.
Here is a case, where the constructor needs to be able to take both types
(scope and heap), and the compiler will not be able to which to use without
semantic analysis.
class DelegateCaller
{
private delegate int _foo();
this(int delegate() foo) { _foo = foo; }
int callit() { return _foo();}
}
int f1()
{
int x() { return 5; }
auto dc = new DelegateCaller(&x); // should allocate on stack
return dc.callit() * dc.callit();
}
DelegateCaller f2()
{
int x() { return 5;}
auto dc = new DelegateCaller(&x); // allocate on heap
return dc;
}
So the author of DelegateCaller cannot require a heap delegate, even though
it's possible the act of creating a DelegateCaller can cause an escape.
Note that the first two lines of each function are identical, so the
compiler needs to do a semantic analysis of whether the use of a delegate
requires a heap allocation. It would be even more sticky with multiple
function calls, or functions that call eachother.
The only thing I can think of is to leave it up to the caller to decide
whether he thinks the delegate should be heap-allocated, and the author of
the function should document how it will use the delegate.
Fortunately, this is not a huge deal, as most of the time a developer
expects a stack-allocated delegate (scope). So make scope the default and
allow some syntax to let the author define that a function call warrants
allocating the frame on the heap.
-Steve
More information about the Digitalmars-d
mailing list