Problem with closures

David Medlock noone at nowhere.com
Thu Jan 11 04:51:22 PST 2007


Alain wrote:

> Hello,
> 
> I am experimenting with closures and i have problem with the following code:
> 
> import std.stdio;
> alias int delegate(int x) AddFunc;
> 
> AddFunc addN(int n) {
>     int add(int i) {
>         return i + n;
>     }
>     return &add; // the add function captured will remember the value of n
> }
> 
> void apply(int[] array, AddFunc func) {
>     foreach (inout int i; array) {
>         i = func(i);
>     }
> }
> 
> int main() {
>     int[] numbers = [1,2,3];
>     writefln("numbers before=",numbers);
>     apply(numbers, addN(40)); // add 40 to each number
>     writefln("numbers after=",numbers);
>     return 0;
> }
> 
> The result should be [41,42,43] but i get [4202694,4202695,4202696]
> 
> Am i missing something?
> 
> Alain

D doesn't support true closures, just delegates.  Local variables in 
functions are still allocated on the stack and therefore invalid after 
you return from them.

You must use objects for this purpose.

-DavidM


More information about the Digitalmars-d-learn mailing list