What is the difference between the const
and immutable
type qualifiers in D?
Immutable makes the contract that this object will not change, whatsoever (e.g. Python tuples, Java strings). Const makes the contract that in the scope of this variable it will not be modified (no promise whatsoever about what other threads might do to the object pointed to during this period, e.g. the C/C++ keyword).
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.
If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
Something that is const
cannot be mutated via that reference but could be mutated by a mutable reference to the same data. Something that is immutable
can't be mutated by any reference to that data. So, if you have
const C c = foo();
then you know that you cannot mutate the object referred to by c
through c
, but other references to the object referred to by c
may exist in your code, and if they're mutable, they could mutate it and therefore change what c
sees. But if you have
immutable C c = foo();
then you know that it's not possible for the object referred to by c
to change. Once an immutable
object has been constructed, it's illegal for it to be mutated, and unless you subvert the type system via casting, it's not even possible to have a mutable reference to an immutable
object. And since immutable
objects can be put into read-only memory if the compiler chooses to, you could actually get segfaults and the like if you ever tried to cast away immutable
and mutate the object. The same goes for const
, since a const
reference could actually refer to an immutable
object. Casting away either const
or immutable
and then mutating the then mutable object is undefined behavior and should basically never be done.
And since an immutable
object can never be mutated even by another reference, reading an immutable
object from multiple threads is completely thread-safe. So, immutable
objects are implicitly shared across threads, whereas everything else which isn't explicitly marked with shared
is considered thread-local. immutable
also provides better optimization opportunities to the compiler than const
does, because it's guaranteed to never change, whereas a const
object can change through another reference to the same data.
For value types, there isn't really much difference between const
and immutable
(since you can't have mutable references to non-mutable value types), but for reference types, there is a significant difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With