const=readonly invariant=const

Daniel919 Daniel919 at web.de
Wed Jan 2 06:25:59 PST 2008


> What's the difference between "const T" and "invariant T", if T is a 
> value type (builtin type or struct)?
> 
> Value types are always a copy and never refer to anything.
> So a const(T) can't be changed.

There is a little difference:
struct St { T ptr2sth; } //T is a class or a pointer to sth

const St st = St(&sth);
st.ptr2sth is an invariant ptr to: sth that might change

invariant St st = St(&someobj);
st.ptr2sth is an invariant ptr to: sth that will never change

However,
const(valuetype) is always equivalent to invariant(valuetype)
That's also why: const Foo* ptr2foo;
a const ptr to a const Foo <=> an invariant ptr to a const Foo

So the distinction between const and invariant is only important, when 
it comes to the question, what a ptr is pointing to:
1. const(Foo)* ptr2constfoo = &foo;
2. invariant(Foo)* ptr2invariantfoo = &foo;


My opinion

is that const reads like: this will never change
I know there is no difference between 
const,invariant,readonly,immutable,... in the English language.
And that in C++ const also doesn't mean "this will never change".

But I think, the best fitting one to express what we really
want in case 1 is: readonly
Because it stands for what we intend to do:
Use this ptr to read Foo only.
So a ptr to sth readonly means: readonlyview
AND NOT: ptr to readonly data
(just like function params in,inout,out express what we intend to do)


Of course one could argue that readonly reads like:
this Foo is readonly and thus will never change.

But for const it's the other way round:
I argue that const reads like:
this Foo is const and thus will never change
And not that it means: we can only read this Foo from this ptr (but
it might get changed from somewhere)

It's the problem that all these words are synonyms in the English language.


But I can better live with:
readonly(T)* to mean: ptr that is used to read only
and NOT to mean: ptr to sth that will never change

than
const(T)* to mean: ptr that is used to read only
and NOT to mean: ptr to sth that will never change


This way
const T foo = ...;
would mean that nothing of foo will ever change.
With the current system, you would have to use invariant.
But then, for consistency, you should not use
"const x = 1;" but "invariant x = 1;"
So you would mostly use invariant, and const only where you want to say:
ptr that is used to read only

But then it would be easier if we change:
const to readonly
invariant to const


You can give it a try, just compile like:
cat ./test.d | sed -e 's/const/invariant/g;s/readonly/const/g' > test2.d 
&& dmd.exe test2.d | sed -e 's/const/readonly/g;s/invariant/const/g' && 
./test2


Best regards,
Daniel



More information about the Digitalmars-d mailing list