Delegates: Print 0..9
Timon Gehr via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Dec 2 13:45:06 PST 2016
On 01.12.2016 21:12, Ali Çehreli wrote:
>
>
> This is a common issue with D and some other languages (as I had learned
> during a Dart language presentation, of which Dart does not suffer
> from). All those delegates do close on the same loop variable. You need
> to produce copies of the variable.
This is a common misconception. It's an implementation bug. The
variables /are/ distinct. It is actually memory corruption. Evidence:
import std.stdio;
void main(){
int delegate()[] dgs;
foreach(immutable i;0..10){
dgs~=()=>i; // i is immutable
}
foreach(dg;dgs) writeln(dg()); // yet changes
dgs=[];
foreach(i;0..10){
int j=i; // creating a new variable
dgs~=()=>j;
}
foreach(dg;dgs) writeln(dg()); // does not help
}
More information about the Digitalmars-d-learn
mailing list