[Issue 2043] Closure outer variables in nested blocks are not allocated/instantiated correctly: should have multiple instances but only have one.

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Thu Oct 2 09:02:50 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=2043

hsteoh at quickfur.ath.cx changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |hsteoh at quickfur.ath.cx

--- Comment #13 from hsteoh at quickfur.ath.cx ---
Note that this bug breaks immutability:

---------
import std.stdio;

void main() {
    void delegate()[] a;
    foreach (i; 1 .. 10) {
        immutable j = i;
        writeln(j);
        a ~= { writeln(j); };
    }
    writeln("---");
    foreach (f; a) {
        f();
    }
}
---------

Output:
---------
1
2
3
4
5
6
7
8
9
---
9
9
9
9
9
9
9
9
9
---------

Notice that in each iteration of the loop, we are closing on the immutable
value j, which is set to the loop counter. However, the output shows that the
value of j has changed since the delegates were initialized. In fact, it
changes at every iteration. This violates the guarantee of immutable.

--


More information about the Digitalmars-d-bugs mailing list