Final, Const, Invariant

Don Clugston dac at nospam.com.au
Mon Mar 26 01:43:39 PDT 2007


Dan wrote:
> Andrei Alexandrescu (See Website For Email) Wrote:
> 
>> Lutger wrote:
>>> David B. Held wrote:
>>>> Since the Extended Type Design thread has blown my stack (and taken 
>>>> all the heap in my mail reader), here is my explanation of these 
>>>> concepts for anyone who might still be confused.  Yes, the explanation 
>>>> is cartoony, but I hope it helps:
>>>>
>>> Haha thanks, only know I understand it clearly, time to read some of 
>>> that thread again...
>>>
>>> It is much clearer though than C++, for there it depends on where you 
>>> put the const which kind of meaning it has.
>>>
>>> To sum it up, there are three kinds of 'immutability', where one (const) 
>>> is a subset of another (invariant). With this, we can control the 
>>> semantics we want precisely and combine them to get a grand total of 
>>> five different meanings:
>>>
>>> final Object x = y; // x won't ever reference anything but y
>>> const Object* x = &y; // y can't be changed by x
>>> invariant Object x = new Object; // x can't be changed at all
>>> final const Object* x = &y; // x points to y forever and can't change y
>>> final invariant Object* x = &y; // same as above but y will never change
>>>
>>> This is right?
>> Yah.
>>
>> Andrei
> 
> I think the concept is right.
> 
> Details, thoughts on which word ought to mean which?  I agree we should use three keywords to accomplish the storage class thing.  Note though that const and invariant are already keywords, and this might break some things...

My code has const everywhere. In fact, I use 'const' about ten times as 
often as 'static' or 'class'. And the new scheme does not seem to have a 
direct equivalent for it. How can I say, "I want to refer this literal 
by a name, but in all other respects I want it to behave exactly as a 
literal"? In particular, I do not want storage associated with it 
(attempting to take its address is a bug), and it should work with CTFE.

There's an ugly hack where you can use an anonymous enum, but it only 
works for integral types; does not work for floating point or string 
literals. Note that named floating point constants are extremely common 
in scientific code. In fact, it's almost always bad style to use an 
unnamed floating point literal!
If 'const' is used as described in the new scheme, seriously consider if 
we need a 'literal' or 'define' keyword.

Since I suspect that I'm losing the battle for 'const'=='literal', I 
have a suggestion. The best word I've come up with for what the proposed 
'const' means is 'constrained'. Which is interesting because of the way 
you'd abbreviate it...

eg.
const Object* x = &y; // y can't be changed by x
--> x is constrained in what it can do to y.

'const' could be described as an abbreviation of 'constrained' rather 
than 'constant'.



More information about the Digitalmars-d mailing list