www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Mutable class reference to immutable class

reply Jonathan Marler <johnnymarler gmail.com> writes:
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.
Sep 10 2016
parent Lodovico Giaretta <lodovico giaretart.net> writes:
On Saturday, 10 September 2016 at 19:46:51 UTC, Jonathan Marler 
wrote:
 This is been bugging me for a while. Is it possible to have a 
 mutable reference to an immutable class?  [...]
You are probably looking for std.typecons.Rebindable: https://dlang.org/phobos/std_typecons.html#.Rebindable
Sep 10 2016