Dynamic closure vs static closure

Johan Granberg lijat.meREM at OVEgmail.com
Sat Oct 25 10:50:27 PDT 2008


Bill Baxter wrote:

> On Sat, Oct 25, 2008 at 6:30 PM, KennyTM~ <kennytm at gmail.com> wrote:
>> 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( scope 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.
>>
>> It should done on the calling site (the point where delegates are
>> created). Why the called function need to know if the delegate is a
>> closure or not? What they can do is just call the delegate.
> 
> The problem is this
> 
> {
>     float x = 3.14;
>     bar( float delegate (float y){ return x*y ; } );
>       // this delegate need to be allocated?
> }
> 
> If bar is going to hold onto the delegate beyond the end of the scope,
> then allocation is needed.  The author of bar() may be in a better
> position to judge that than the caller of bar().  But I'm not sure if
> that's the only kind of situation to be concerned about.  Are there
> other cases where only caller knows which it should be?
> 
> --bb

What about the case of storing a bunch of delegates in a list (thats retaining them) that has a lifetime shorter than the function context?

In this case it would be more efficient to store stack delegates even when some code keeps a reference.

I don't believe that there is a non-problematic way to determine if a delegate has to be on the heap or not. I suggest that this decision is left to the programmer by making heap allocation the default and allowing the calling side to optimize by adding some keyword, for example scope.

For the case of calling library code the programmers will have to rely on documentation.




More information about the Digitalmars-d mailing list