Modifing local variables with anonymous delegate?

Gordon me at home.com
Thu Dec 26 15:23:00 PST 2013


Hello,

A question regarding delegates and local variables:
I have the following code, which seems to indicate the delegate 
function can access "b", but makes a private copy of it, instead 
of using the "real" b.
---
import std.stdio;
import std.algorithm;

void main()
{
         int[] a = [1,1,1];
         int b = 42;

         auto c = map! ( delegate(x) { ++b; return x+b ; } )(a);

         writeln("a = ",a);
         writeln("b = ",b);
         writeln("c = ",c);
}
---

--- The output ---
$ rdmd test.d
a = [1, 1, 1]
b = 42
c = [44, 45, 46]
---

Because the values in "c" are increasing, it means there is some 
copy of "b" which is incremented (from inside the delegate 
function).
But the "b" in "main" retains its original value of 42.

What's going on?
and is there a way to "fix" it (i.e. have a delegate update a 
local variable) ?

I've found few old discussions, mentioning "copy of stack 
variables" [1,2] and different kinds of closures [3], but I 
wasn't able to figure it out (I'm new to D).

Thanks,
  -gordon

[1] Anonymous Delegates(from 2008): 
http://forum.dlang.org/post/g36kpk$15rb$1@digitalmars.com
[2] Local vars in delegates(from 2009): 
http://forum.dlang.org/thread/hgshuk$1620$1@digitalmars.com
[3] Static vs Dynamic closures? (from 2008): 
http://forum.dlang.org/thread/ghu3m3$1e6o$1@digitalmars.com


More information about the Digitalmars-d mailing list