On 06.03.2018 17:19, Steven Schveighoffer wrote:

unittest {
     int n = 0;
     struct S {
         int fun() const { return n; }
     immutable S s;
     assert(s.fun == 0);
     assert(s.fun == 1); // Not so immutable now, are you?

That's not a demonstration of breaking immutability. counter-proof:

struct S
    static int x;
    int fun() const { return x; }

immutable S s;
assert(s.fun == 0);
assert(s.fun == 1);

In other words, if the struct can access the data considered "outside it's instance", then it it can return it, change it even.

Here's how to break immutability:

void main(){
    int i = 0;
    struct S{
        const(int)* fun()const pure{
            return &i;
    immutable S s;
    static const(int)* foo(immutable(S) s)pure{
            return s.fun();
    immutable(int) *pi=foo(s);
    import std.stdio;
    writeln(*pi); // 0
    writeln(*pi); // 1

The reasoning "the reference is stored in the type yet not part of the type" does not work for pure functions, as then you cannot offer an alternative explanation in terms of an external data store.


Reply via email to