[Issue 4966] New: Loops and closures break immutable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Oct 1 03:42:34 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4966

           Summary: Loops and closures break immutable
           Product: D
           Version: D2
          Platform: Other
        OS/Version: All
            Status: NEW
          Keywords: wrong-code
          Severity: critical
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: nfxjfg at gmail.com


--- Comment #0 from nfxjfg at gmail.com 2010-10-01 03:42:16 PDT ---
Closures referencing immutable variables declared inside a loop can observe how
these immutable values are changing - this should be impossible according to
the definition of "immutable".

$ cat closure.d
import std.stdio;

void main() {
    void delegate() res;
    foreach (i; 0..2) {
        immutable v = i;
        void printi() {
            writefln("ptr=%x value=%d", &v , v);
        }
        if (i == 0) {
            res = &printi;
            res();
        }
    }
    res();
}

$ dmd closure.d
$ ./closure
ptr=b75bae44 value=0
ptr=b75bae44 value=1

As you can see, an immutable variable changed its value. The code above is
SafeD clean, i.e. doesn't use any dirty tricks that would subvert the
typesystem. (Except printing the pointer address, which is just for
demonstrating that it's the same value.)

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list