Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Proper Creation and Use of Stack Delegates

Part of DelegateCategory

Description

This shows some basic example code using stack delegates.

Example

import std.stdio;

/* A stack delegate, like any other delegate, is comprised of two pointers:
 * a funtion pointer, and a data pointer.  The data pointer is passed to the
 * function as an invisible argument (just like 'this' is passed to member
 * functions of a class.
 *
 * In the case of stack delegates, the pointer points to the stack frame where
 * the local variables are stored.  Modifying those variables inside a stack
 * delegate will modify the actual variables in the stack frame.
 */

void bar(void delegate() d) {
  writefln("--- bar( void delegate() d) called --- ");
  d();
}


void foo() {
    int a = 1;
    int b = 2;
    int c = 3;

    writefln("Start foo().
    Initial local values are a = %d, b = %d, c = %d", a,b,c);

    /* note that the stack delegate is declared as a delegate literal here.
     * Internally, the compiler declares an anonymous function, and the pointer
     * to the function is stored as the delegate's function pointer.
     */

    bar(delegate void() { a = 4; b = 5; c = 6; } );

    /* because bar() called the stack delegate, these values have changed */

    writefln("After calling bar(delegate) inside foo().
    Changed local values are a = %d, b = %d, c = %d", a,b,c);

    assert(a == 4);
    assert(b == 5);
    assert(c == 6);
}



int main() {
    foo();  
    return 0;
}

Source

Original contribution by Russ Lewis. Changed based on suggestions by Blandger.