D const design rationale

Walter Bright newshound1 at digitalmars.com
Fri Jun 22 01:07:30 PDT 2007


Sean Kelly wrote:
> Walter Bright wrote:
>> http://www.digitalmars.com/d/const.html
> 
> So in short, 'const' protects data and 'final' freezes references.  How 
> do these two apply to an int declaration?
> 
>     const final int x = 5;
> 
> Is either a compiler error? are they synonyms in this case?

It's not an error, it's just redundant.


> This aspect of the design seems very straightforward, aside from the 
> question above.  What bothers me, however, is the use of 'invariant'. 
> Adding a third keyword simply to represent data that's "really really 
> const" just confuses things to me, and I haven't been able to get past 
> this.

invariant = the data doesn't change
const = the data cannot be changed through this reference to it

> Given that adding a third keyword doubles the number of 
> permutations for describing const behavior, I think the addition of 
> 'invariant' should be very carefully considered.  Is there any way we 
> could get along without it?  I realize that 'invariant' would be rarely 
> used in practice, but that doesn't change the impact an additional 
> attribute has on the complexity of this design.

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.


> Frankly, I think we could almost get away with one keyword, but for the 
> fact that D doesn't use a reference qualifier for class references. 
> About the only workaround I could think of to describe a const reference 
> to mutable data would be something like this:
> 
>     const (ref MyClass) x;
> 
> And inserting the 'ref' seems even more confusing than simply having 
> 'final' as in the current design.

C++ tries too hard to use one keyword to do it all. The result is, as 
the article showed, serious difficulties.



More information about the Digitalmars-d mailing list