May 01, 2011
I saw examples in the D Programming Language book (Page 256) where opAssign() took a ref argument instead of a const ref. So I figured I would test it out and see if the compiler complains if I try to assign a const or immutable struct to another one.

import std.stdio;

struct Foo
{
    auto ref opAssign(ref Foo s)
    {
        s.x = 4; // modifying mutable object !!!
        x = s.x;
        return this;
    }

    private int x = 0;
}

void main(string[] args)
{
    immutable(Foo) foo = Foo();
    auto foo2 = Foo();
    writefln("(immutable!) foo.x = %s", foo.x); // prints 0
    foo2 = foo; // allowed immutable RHS ???
    writefln("(immutable?) foo.x = %s", foo.x); // prints 4
}

Turns out it doesn't, and it seems to violate immutability. Is there something I am misunderstanding here?

The example above compiles with both gdc and dmd for D2. It also works with immutable replaced by const.

Ashish
May 01, 2011
Ashish Myles Wrote:

>      foo2 = foo; // allowed immutable RHS ???

Allowing this is a bug. File it in bugzilla.

Unfortunately, lazy objects "mess up" the expected const correctness of Object. Even if they are logically const, lazy objects can't always be passed as const.