const/immutable violation?
Ashish Myles
marcianx at gmail.com
Sat Apr 30 17:40:09 PDT 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
More information about the Digitalmars-d-learn
mailing list