What functions can be called on a shared struct that's implicitly castable to immutable?

Simen Kjærås simen.kjaras at gmail.com
Sun Nov 3 13:54:57 PST 2013


Consider:

module foo;

struct S {
     immutable(int)[] arr;
     void fuzz() const pure {
     }
}

void bar(S s) {
     s.fuzz();
}

void main() {
     shared S s;
     bar(s);   // a
     s.fuzz(); // b
}


In this case, the line marked 'a' works perfectly - it compiles and does 
what I'd expect it to.

However,the line marked 'b' does not compile - " non-shared const method 
foo.S.fuzz is not callable using a shared mutable object ".

The reason for this is that fuzz takes the 'this' pointer by reference, 
and so risks that another thread corrupt the internal state while it's 
working.

Seeing as line 'a' works, it seems safe for line 'b' to make a copy 
behind the scenes (structs in D are defined to have cheap copying, I 
seem to recall) and call fuzz on that copy - the type system claims that 
the call to fuzz cannot possibly change the state of the struct on which 
it is called.

With the state of 'shared' as it is, I'm unsure if this is a change that 
should be done - it seems perhaps better to wait for a true overhaul of 
the feature.

Where I specifically found a need for this is in attempting to fix bug 
11188[1]. While I have found a workaround, it's needed per function, and 
I'm pretty sure it'll break some specific other cases.

[1]: http://d.puremagic.com/issues/show_bug.cgi?id=11188

--
   Simen


More information about the Digitalmars-d mailing list