Logical const

Peter Alexander peter.alexander.au at gmail.com
Sun Nov 28 11:01:16 PST 2010


On 28/11/10 3:45 PM, Jonathan M Davis wrote:
> Oh, I agree that the lack of logical const is a problem, but allowing for
> mutable member variables within a const object is a whole in the const system,
> and Walter, at least, is convinced that doing so is completely broken.

Mutable member variables are only a hole in the const system if the 
const system is overly strict about what const is. In C++, I view 
mutable as an extension to the const system that allows one to define 
member variables that are attached to an object, but ultimately do not 
affect the observable state of the object.

You mentioned having an external cache of Matrix determinants. One way 
to view mutable would be to see it as an automation and optimisation of 
this external cache (optimised because it stores the cache right inside 
the object, rather than in a slow external hash table).

> Certainly, because of immutable in D, I have to agree that in the general case,
> it wouldn't work. Without immutable, you could presumably get something similar
> to what C++ has (if you could ever get Walter to go for it), but once you have
> immutable, that doesn't work anymore, since anything that's const could actually
> be immutable, and then it's _definitely_ impossible to change it.

Then perhaps what is needed is an intermediate level of immutability.

immutable - Data will never, ever change, through any reference.
const - Data will never change through this reference.
newlevel - Data will never logically change through this reference.

The idea here is that you would use this newlevel normally (like you use 
const normally) and only use this new const when you actually desire 
strict const-ness e.g. when you are using the resource concurrently.

I'll happily admit that it's starting to get on the complex side, but as 
far as I'm concerned, const in D as it is now is simply unusable. I will 
happily write const correct code, but not when it means giving up the 
possibility of writing memoized functions.



More information about the Digitalmars-d mailing list