any news on const/invariant?

Janice Caron caron800 at googlemail.com
Thu Nov 29 01:42:10 PST 2007


Hope yall were paying attention and spotted that I screwed that up
completely. It should of course have been:

   class A
   {
       this(int n) { x = n; }
       int x;
       const int f() { return x; }
       invariant int g() { return x; }
   }

   A ma = new A(3);
   writefln(ma.f()); /* OK */
   writefln(ma.g()); /* error */

   const A ca = new A(3);
   writefln(ca.f()); /* OK */
   wriitefln(ca.g()); /* error */

   invariant A iaTemp = cast(invariant(A)) new A(3);
   writefln(ia.f()); /* OK */
   writefln(ia.g()); /* OK */

Anyway, here's the deal. When you declare a function as const, it
means that the variable "this" is const during the function's
execution. Likewise, when you declare a function as invariant, it
means that the variable "this" in invariant during the function's
execution.

In both cases, the callee code will fail to compile if the function
modifies any member variable.

The difference between the two is visible at the caller site, however.
A pointer can always be cast to const, so calling a function declared
as const is always OK. However, only no pointer can ever implicitly
cast to an invariant pointer (unless it was invariant to begin with),
so code at the caller site which tries to call an invariant function
will not compile, unless the class instance in invariant.

Of course, getting an invariant instance in the first place requires a cast!



More information about the Digitalmars-d mailing list