Const-correctness - const and immutable in D

const and immutable in D

In Version 2 of the D programming language, two keywords relating to const exist. The immutable keyword denotes data that cannot be modified through any reference. The const keyword denotes a non-mutable view of mutable data. Unlike C++ const, D const and immutable are "deep" or transitive, and anything reachable through a const or immutable object is const or immutable respectively.

Example of const vs. immutable in D

int foo = new int; // foo is mutable. const int bar = foo; // bar is a const view of mutable data. immutable int baz = foo; // Error: all views of immutable data must be immutable. immutable int nums = new immutable(int); // No mutable reference to nums may be created. const int constNums = nums; // Works. immutable is implicitly convertible to const. int mutableNums = nums; // Error: Cannot create a mutable view of immutable data.

Example of transitive or deep const in D

class Foo { Foo next; int num; } immutable Foo foo = new immutable(Foo); foo.next.num = 5; // Won't compile. foo.next is of type immutable(Foo). // foo.next.num is of type immutable(int).

Read more about this topic:  Const-correctness