The Status of Const

Walter Bright newshound2 at digitalmars.com
Fri Aug 13 13:25:37 PDT 2010


Graham St Jack wrote:
> For me, the key problem is that a class object reference has the same 
> const/immutable/shared attribute as the object on the heap that it 
> refers to. This is sometimes what you need, but more often you want a 
> non-shared, mutable reference to a const/immutable/shared object.

I struggled with this for a long while before I eventually came to the 
conclusion that I was thinking about class objects as a reference and the 
instance, and that those two were separable concepts. They are not. A reference 
type is implicitly treated like a value type as far as accessing its members go. 
Trying to separate out the two is a fundamental misunderstanding of what 
reference types are all about. Semantically, they are much more than just a 
pointer to the instance.


> You can achieve this with pointers for arrays, structs and primitive 
> types, but not with classes because a class pointer is just a pointer to 
> a reference.

The way to do it with class is take a pointer to the class:

   class C { ... }

   const(C)*[];    // array of pointers to const classes

just like you'd do with a struct.


More information about the Digitalmars-d mailing list