Search⌘ K

Delegates

Learn how delegates in D combine function pointers with execution context to safely manage variable lifetimes. Understand closures and how delegates maintain local state beyond its scope, enabling advanced function manipulation and event handling within your D programs.

Delegates: Definition

A delegate is a combination of a function pointer and the context that it should be executed in. Delegates also support closures in D. Closures are a feature supported by many functional programming languages.

As we discussed in the lifetimes and fundamental operations chapter, the lifetime of a variable ends upon leaving the scope that it is defined in:

{
    int increment = 10; 
    // ...
} // ← the life of 'increment' ends here

That is why the address of such a local variable cannot be returned from a function.

Let’s imagine that increment is a local variable of a function that itself returns a function. Let’s make it so that the returned lambda happens to use that local variable:

D
alias Calculator = int function(int);
Calculator makeCalculator() {
int increment = 10;
return value => increment + value; // ← compilation ERROR
}
void main() {
makeCalculator();
}

That code is in error because the returned lambda makes use of a local variable that is about to leave the ...