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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…