This is been bugging me for a while. Is it possible to have a
mutable reference to an immutable class? In other words, can you
set a class variable to an immutable class, and then set that
variable to another immutable class later?
Mutable "slices" to immutable data are easy:
immutable(char[]) x = "string for x"; // immutable data x
immutable(char[]) y = "string for y"; // immutable data y
immutable(char)[] mutableRef = x; // mutable slice to
immutable data
mutableRef = y; // OK, you can set mutableRef to another
immutable slice
But I can't figure out how to make a mutable "class" to immutable
classes:
immutable(SomeClass) x = new immutable SomeClass(); //
immutable class x
immutable(SomeClass) y = new immutable SomeClass(); //
immutable class y
immutable(SomeClass) mutableRef = x;
mutableRef = y; // Error: cannot modify mutable expression
mutableRef
A workaround would be to make mutableRef an
immutable(SomeClass)*, but this adds an extra level of
indirection. Since all classes in D are pointers, x is already a
pointer, so making a pointer to x would be making a pointer to a
pointer that points to a class.
It's obvious this issue is a result of the fact that all class
variables are pointers. I don't suppose there is a way to
represent a class's value type that I don't know about is there?
SomeClass.ValueType? // Is there semantics for this I don't
know about?
If so, you could solve the problem by declaring mutableRef as:
immmutable(SomeClass.ValueType)* mutableRef = x;
I haven't encountered semantics for this anywhere in the
language, but maybe someone else can enlighten me? If not, is
there another way to get a mutable reference to an immutable
class? Thanks in advance for the help.