www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Enforcing static closure

reply Piotr Szturmaj <bncrbme jadamspam.pl> writes:
I want to make a delegate of blocking I/O statement and pass it to a 
function. Then it will be called immediately. This delegate never 
escapes its creation scope, so I don't want heap closure allocation.

Will compiler create dynamic closure (e.g. with allocation) or static 
closure (with pointer to the stack)?

void recv(ubyte[] buf, out size_t len)
{
     // block until data is received
}

int numWaiters;

// will that "scope" enforce static closure?
void wait(scope void delegate() dg)
{
     numWaiters++;
     dg();
     numWaiters--;
}

void test()
{
     ubyte[] buf = new ubyte[1500];
     size_t len;

     wait( { recv(buf, len); } );
}
May 19 2011
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Thu, 19 May 2011 15:39:12 -0400, Piotr Szturmaj <bncrbme jadamspam.pl>  
wrote:

 I want to make a delegate of blocking I/O statement and pass it to a  
 function. Then it will be called immediately. This delegate never  
 escapes its creation scope, so I don't want heap closure allocation.

 Will compiler create dynamic closure (e.g. with allocation) or static  
 closure (with pointer to the stack)?

 void recv(ubyte[] buf, out size_t len)
 {
      // block until data is received
 }

 int numWaiters;

 // will that "scope" enforce static closure?
 void wait(scope void delegate() dg)
 {
      numWaiters++;
      dg();
      numWaiters--;
 }

 void test()
 {
      ubyte[] buf = new ubyte[1500];
      size_t len;

      wait( { recv(buf, len); } );
 }

In this case, a closure should *not* be created. A closure is created when you create a delegate to an inner function UNLESS: a. The expression which takes the delegate is being used to pass the delegate to a function AND b. The function's delegate parameter is marked 'scope' or 'in' Note that the following still would create a closure: auto dg = {recv(buf, len);}; // forces a closure. wait(dg); because you aren't passing the delegate to the scope function at the time of delegate creation. dmd is kind of silly about that. -Steve
May 19 2011