mutable keyword

chmike via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 22 07:22:24 PDT 2016


There is a benefit in not allowing to get pointers to class 
members. It allows to have movable object instances and this give 
access to some faster GC algorithms like generational garbage 
collection which is in use in Java.

As an old C++ programmer and newbee in D programming, the D 
constness and immutability concepts are confusing. They are so 
strong that I hardly see any use for them with objects.

There would be a much wider use to be able to tell user that he 
may assume the object is constant from the interface point of 
view. This is a huge help in code readability and program 
validity checking. I had the impression that this is the 
principle used for the pure keyword.


I would vote against the introduction of the mutable keyword as 
it exist in C++ because it is a half backed solution. First it 
tells the compiler that this variable is modifiable at any time 
by any method of the class. This is way I always felt 
uncomfortable using mutable. It punches a big hole in the 
constness protection.

The other problem is with inheritance (I know it's old school, 
but ok). If a derived class needs to modify a member variable of 
a base class that wasn't declared mutable, you're stuck. That is 
why C++ introduced the const_cast. This is much better in that 
the hole in the constness protection is very limited, but the 
code is also less pleasant to read.

How could be the D way to solve this ? My feeling is that it 
could be by introducing a mutate{...} block. All instructions in 
that block would be allowed to modify the const object. The 
developer intent would be clear, the code readable and the hole 
limited.

The difference with the C++ model is that in C++ we switch off 
the constness flag of member variables for a persistent or short 
time, in D we would switch off constness control in a block of 
instructions.

I didn't thought of all the implications yet.

I only talked about const objects. I still need to find a use 
case for immutable objects /S


More information about the Digitalmars-d-learn mailing list