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 ...
Get Learning D now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.