Transitive const sucks

Sean Kelly sean at f4.ca
Tue Sep 11 07:46:58 PDT 2007


Janice Caron wrote:
> On 9/11/07, *Alex Burton* <alexibu at mac.com <mailto:alexibu at mac.com>> wrote:
> 
>     The idea that you can just 'get' a value from memory without
>     modifing anything is an illusion created by the computer.
> 
> 
> Yes, it's even more obvious with a read than with a write.
> 
> Another interesting use-case involves caching. I'll spare you the boring 
> details, but the essence is, I once had a class member function that did 
> a lookup, much like an associative array, and the prototype would have 
> been something like
> 
>  int lookup(int key) const;
> 
> This was C++, so the const was at the end. The thing is, all the data 
> was in a file, and so the function had to open a file, read it, close 
> the file, and return the data. Well, naturally, it cached some data 
> internally to avoid too many file accesses. And - also naturally - I did 
> not load the entire file into memory at constructor time because huge 
> parts of it might not be needed at all. The file access was deferred 
> until it was needed, and cached appropriately.
> 
> So the function was declared const, because /conceptually/ it was.
> 
> But the class had a mutable cache, declared with the C++ keyword "mutable"
> 
> Transitivity would wreck that.

My classic example for the need of "mutable" is a mutex used to 
synchronize access to class data.  The mutex must be modified even for 
read operations.  But for better or worse, D const has a different aim. 
  The goal is largely to produce a system which allows for compiler 
optimization rather than to enforce some sort of logical restrictions on 
behavior.  I suspect this means that D apps won't look very much like 
C++ apps in terms of how const is used, and the overall utility for the 
average programmer may well be somewhat small.


Sean



More information about the Digitalmars-d mailing list