Objects with const and immutable
In the context of class and struct instances, it's easier to understand the relationship const
and immutable
have with data. Here's a simple example:
struct ModMe { int x; } void main() { immutable ModMe mm; immutable(ModMe)* pmm; mm.x = 1; // Error pmm.x = 2; // Error }
The declaration of mm
creates an instance of type immutable(ModMe)
. Not only can no assignments be made to mm
, mm.x
cannot be modified. pmm
is a pointer to immutable data, so the pointer can be reassigned, but pmm.x
cannot be modified. Now look at this:
struct ModMeHolder { ModMe mm; } void main() { immutable ModMeHolder mmh; mmh.mm.x = 1; }
As immutable
is transitive, applying it to mmh
causes mm
to also be immutable. If, in turn, it had any class
or struct
instance members, they would also become immutable. As they say, it's turtles all the way down. The same is true for const
, but recall that its contract is not as strict as that of immutable...