Question about anonymous delegates.
Timon Gehr
timon.gehr at gmx.ch
Wed Oct 3 07:04:40 PDT 2012
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);
}
}
More information about the Digitalmars-d-learn
mailing list