D const design rationale

Walter Bright newshound1 at digitalmars.com
Fri Jun 22 11:37:33 PDT 2007


Sean Kelly wrote:
> Walter Bright wrote:
>> In C++, sometimes const means invariant, and sometimes it means 
>> readonly view. I've found even C++ experts who don't know how it works.
> Odd.  The C++ system always seemed extremely simple to me.

It isn't. I run into people all the time who are amazed to discover that 
const references can change. Few understand when const is invariant and 
when it isn't. I've never even seen anyone mention the problem where the 
non-transitive const destroys any hope of having FP like capabilities in 
C++.


> I personally find the use of three keywords to represent three 
> overlapping facets of const behavior to be very confusing, and am 
> concerned about trying to explain it to novice programmers.  With three 
> keywords, there are six possible combinations:
> 
> final
> const invariant
> final const
> final invariant
> const invariant
> final const invariant

Probably the thing to do is simply outlaw using more than one.

> That some of these may be redundant just serves to further confuse the 
> issue in my opinion.  So I wondered whether one of the keywords could be 
> done away with.  Previously, you said 'invariant' may only apply to data 
> whose value can be determined at compile-time, thus I imagine it can 
> only apply to concrete/data types (ie. not classes).  Assuming this is 
> true, I wonder whether there is truly a point in having 'invariant' at 
> all.  Assuming it were done away with, the system becomes much simpler 
> to me:
> 
> final
> const
> final const
> 
> And that's it.  'final' means a reference cannot be rebound, 'const' 
> means the data cannot be altered (through the reference), and 'final 
> const' means that both the reference is frozen and the data cannot be 
> changed.  And that's it.

It's missing the transitive nature of invariant.



More information about the Digitalmars-d mailing list