D const design rationale

Sean Kelly sean at f4.ca
Fri Jun 22 11:49:21 PDT 2007


Daniel Keep wrote:
> 
> Sean Kelly wrote:
>> ...
>>
>> 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.  That the existence of invariant required the
>> addition of parenthesis on class invariants just serves to strengthen
>> the argument in my mind.  So in short, I'm just not convinced that
>> 'invariant' provides enough utility to warrant the cost in complexity
>> and broken consistency (unittest doesn't require parens, so why does
>> invariant?).
> 
> What makes me uneasy about the above is that final isn't a type
> constructor: it's a storage class.  You're turning it into
> sorta-kinda-but-not-quite both.  So, you end up with:
> 
> final int x;		typeof(x) == int;
> const int y;		typeof(y) == const int;
> final const int z;	typeof(z) == final const int;

Hm.  Just to clarify, we both agree that the value of a final integer 
(ie. case 1 above) is effectively constant, correct?

> "Wait; why is final part of the last type, but not the first?"  And what
> does this mean if you want a class member with final-style binding, but
> (final const) type semantics?
> 
> final (final const(int*)) foo;
> 
> As opposed to
> 
> final invariant(int*) foo;

Perhaps I'm missing something, but I would rewrite this as:

final const int* foo;

Thus foo cannot be reassigned once set and the data foo refers to may 
not be changed through foo.  This is a slightly weaker guarantee than:

final invariant int* foo;

Which says that the data foo refers to is immutable, but I am skeptical 
that this guarantee actually matters much to users.

Or am I completely misunderstanding?  And why the parenthesis in the 
second declaration?

> I think the thing here is that you're shifting the complexity from
> invariant into final; instead of invariant meaning two different things
> with two very different appearances, you've got final meaning two
> slightly different things with almost identical looks.

I only see final meaning one thing: that the associated value may not be 
reassigned.  For concrete types like integers this is effectively the 
same as const, but as Walter said, the integer would be addressable when 
final but not when const.  Perhaps this is the source of confusion?


Sean



More information about the Digitalmars-d mailing list