digitalmars.D.learn - Enforcing static closure
- Piotr Szturmaj (23/23) May 19 2011 I want to make a delegate of blocking I/O statement and pass it to a
- Steven Schveighoffer (15/38) May 19 2011 In this case, a closure should *not* be created. A closure is created
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
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