A little bug

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Dec 25 18:06:07 PST 2011


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..


More information about the Digitalmars-d mailing list