Inherited const when you need to mutate

Timon Gehr timon.gehr at gmx.ch
Tue Jul 10 17:20:32 PDT 2012


On 07/11/2012 01:57 AM, Walter Bright wrote:
> On 7/10/2012 4:16 PM, Timon Gehr wrote:
>> Const is stronger than what is required to bridge the gap between
>> mutable and immutable. It guarantees that a reference cannot be used to
>> mutate the receiver regardless of whether or not the receiver is
>> immutable underneath. That is unnecessary as far as immutable is
>> concerned. It only needs to guarantee that the receiver does not change
>> if it is immutable underneath.
>
> If you have a const function that accepts both mutable and immutable
> args, then that function *by definition* cannot tell if it received
> mutable or immutable args.
>

I understand. The trick is to disallow creating immutable instances of a 
class which is allowed to mutate the receiver in const methods.
This is essentially your proposal with the casts, but it is type safe.

This removes the 'const' guarantees, but 'immutable' stays
unaffected. Furthermore, functions with closures are type checked at
their creation site and may violate const-transitivity without affecting
'immutable'.

> Furthermore, a const function is saying it will not change, even if
> mutable data is passed to it.
>

A const function is saying nothing at all. Only const pure functions
provide any guarantees.

> Everything falls apart once you allow "logical const" in. You'll be in
> the same boat as C++ const, which is faith-based programming rather than
> checkable programming.

Casting away const because the object one is implementing cannot
support it is faith-based programming.


I for one would be satisfied if inheriting from object became optional:

// object.di
class RawObject /+ this is the root of the class hierarchy +/{ }
class SynchronizableObject : RawObject { void* monitor; }
class Object : SynchronizableObject {
      const { stuff }
}

// user code
class NoCruft : RawObject {
     // ...
}

And if AAs would stop being overly zealous about the opEquals, toHash,
opCmp signatures (why would it need opCmp? I have implemented my own
hash table for now, because I cannot support opCmp.)

The AA should just propagate the signatures to its methods. It will be
@safe to index an AA if the required members are @safe etc.


More information about the Digitalmars-d mailing list