October 03, 2012 Question about anonymous delegates. | ||||
---|---|---|---|---|
| ||||
I found something what I don't understand. Here is a simplifed code with comments: http://dpaste.dzfl.pl/a914d11a I creating anonymous delegates, whose function is to modify their parameter. Their parameters are different class references. I pass these class references to anonymous delegates, but the delegates obtain only the last passed class reference. Thanks for your answers. |
October 03, 2012 Re: Question about anonymous delegates. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sharp | On 10/03/2012 03:53 PM, Sharp wrote: > I found something what I don't understand. > > Here is a simplifed code with comments: > http://dpaste.dzfl.pl/a914d11a > > I creating anonymous delegates, whose function is to modify their > parameter. Their parameters are different class references. > I pass these class references to anonymous delegates, but the delegates > obtain only the last passed class reference. > > Thanks for your answers. class Num { int a; } void main(){ auto nums = new Num[10]; alias void delegate() Func; auto funcs = new Func[10]; // workaround for http://d.puremagic.com/issues/show_bug.cgi?id=2043 ahead: for(int i = 0; i < 10; ++i) (){ Num num = nums[i] = new Num(); int i=i; // fix for bug in your code funcs[i] = {num.a = i;}; }(); foreach(num; nums) { assert(num.a == 0); } foreach(func; funcs) { func(); } foreach(i, num; nums) { assert(num.a == i); } } |
Copyright © 1999-2021 by the D Language Foundation