const/invariant
Steven Schveighoffer
schveiguy at yahoo.com
Wed Dec 5 07:00:28 PST 2007
"Denton Cockburn" wrote
> given a class:
>
> class C {}
>
> what's the difference between:
>
> const C c = new C;
> and
> invariant C c = new C;
>
> From what I can see, neither are modifiable. So what's different
> (D2.008).
const class references can be used to call const member functions, but
cannot call normal member functions or invariant member functions.
invariant class references can be used to call const or invariant member
functions, but not normal member functions.
normal class references can call normal member functions and const member
functions, but not invariant member functions.
In your example, there is no other non-const reference of c, so technically,
it is invariant because nothing outside of the c reference can ever change
it. Therefore, the second declaration is more accurate and gives you more
ability (you can now call invariant functions).
if you had something like:
C c = new C;
const C c2 = c;
invariant C c3 = cast(invariant)c; // this is bad
Now, c2 cannot be declared invariant because something using the c reference
could modify the data. c2 is like a read only view of c, it can look but
cannot touch. c3 is bad because before you cast to invariant, you must
ensure that no other references to the same data can modify the class.
Anticipating your next question: what is the difference between invariant
and const functions? Code-wise, nothing. However, the compiler is free to
make better optimizations knowing that none of the members of the class will
change.
-Steve
More information about the Digitalmars-d-learn
mailing list