www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 16454] New: Return in the body of a foreach in a constructor

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

          Issue ID: 16454
           Summary: Return in the body of a foreach in a constructor
                    backed by opApply corrupts the object
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Mac OS X
            Status: NEW
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: andrepuel gmail.com

import std.stdio;

struct OpApply {
    int opApply(int delegate(int) cb) {
        return cb(42);
    }
}

struct Bolinha {
    int a;
    this(ref OpApply moviadao) {
        foreach(int b; moviadao) {
            this.a = b;
            return;
        }
    }
};

void main() {
    import std.stdio;

    OpApply range;
    writeln(Bolinha(range).a);
}

The expected print result was 42. But I get a random memory garbage instead.
The following minor modification in main will 'fix' the issue:

void main() {
    import std.stdio;

    OpApply range;
    Bolinha littleBall = Bolinha(range);
    writeln(littleBall.a);
}

--
Aug 31 2016