www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - A little bug

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
I've found this sort of bug in xfBuild:

import std.stdio;

class Deps { }
struct Mod {
    Deps deps;
}

void main() {
    Mod[] compileArray;

    foreach (i; 0 .. 2) {
        compileArray ~= Mod(new Deps);
    }

    foreach (mod; compileArray) {
        mod.deps = null;
    }

    foreach (mod; compileArray) {
        writeln(mod.deps is null);  // surprise!
    }
}

This will print "false, false". It's interesting how easy it is to
lose sight of value semantics. I only discovered this bug by chance
and would have easily missed it by eye. The fix is to use "foreach
(ref mod; compileArray)". Even though mod.deps ends up being a
reference to an object, it's the reference itself that ends up being
nulled, not the object itself. E.g.:

class Deps { }
struct Mod {
    Deps deps;
}

void main() {
    Mod mod1 = Mod(new Deps);
    Mod mod2 = mod1;

    assert(mod1.deps is mod2.deps);
    mod1.deps = null;
    assert(mod1.deps !is mod2.deps);
}

Anyway I thought this was interesting. I wonder if this sort of bug is
lurking in some other D codebases out there..
Dec 25 2011
parent "Vladimir Panteleev" <vladimir thecybershadow.net> writes:
On Monday, 26 December 2011 at 02:06:18 UTC, Andrej Mitrovic 
wrote:
 This will print "false, false".
After reading the code, I thought the surprise was that it printed "true" :) Perhaps making the default foreach behavior to make copies of structs wasn't the best idea, also due to performance reasons. One way it could have been designed was to force one of "auto", "const" or "ref" to indicate the "storage class".
Dec 25 2011