Immutable objects and constructor ?
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 20 19:15:46 PDT 2016
On Friday, 20 May 2016 at 20:30:22 UTC, chmike wrote:
>
> I'm a bit surprized that the language doesn't support this. We
> have immutable strings that can be assigned to different
> variables. Why couldn't we do the same with objects ?
Consider this:
immutable(char)[] str;
Here, the array elements of str are immutable, i.e. you cannot do
this:
str[0] = 's'
However, the array reference itself is mutable, so you can freely
assign array references around. This is what string is aliased to.
To prevent the array reference from being assigned:
immutable(char[]) str;
Now trying to assign another string to str will produce a
compiler error.
With arrays and pointers, we distinguish between the data and the
reference. With classes, we do not; there is only the reference.
More information about the Digitalmars-d-learn
mailing list