any news on const/invariant?

Bill Baxter dnewsgroup at billbaxter.com
Wed Nov 28 11:49:19 PST 2007


Janice Caron wrote:
> On Nov 28, 2007 11:45 AM, Don Clugston <dac at nospam.com.au> wrote:
> 
> A thought occurs to me. (And it's a good one). Since we're considering
> making const(this) an attribute, why not extend it to
> const(identifier), for any identifier. That is, const(identifier)
> would syntactically be considered an attribute, and could go anywhere
> version(identifier) could go. It's meaning would be: within the
> specified scope, the named identifier shall be consisdered const (and
> likewise for invariant). Allowing "this" to be merely a special case
> of identifier, does indeed allow us to declare const member functions:
> 
>     const(this) void f();
> 
> as well as the abovementioned grouping.
> 
>     const(this)
>     {
>          int foo();
>          int bar();
>     }
> 
> but, just look what /else/ you could do with it!
> 
>     const(x) /* let x be const within these braces */
>     {
>         /* x is const here */
>     }

I guess in C++ you'd do that by making a const reference to x:

       {
           const int& const_x = x;
           /* use const_x insted of x here
       }

But I can't say that I've wanted to do that very often in C++.  Of 
course the renaming and introduction of indirection that the compiler 
may not optimize away is a bit more cumbersome than what you propose.

Still, even if it wouldn't be particularly useful, the generality is 
elegant. :-)

> or...
> 
>     int x = 42;
>     const(x): /* x is const from here on */
>     x = 100; /* error */
> 
> Why, it's almost like having final back! (Only, with crystal clear
> syntax and without the confusion). Other advantages include

I don't see how it replaces final (aka head-const).  It just allows you 
to move the "const" around and scope it.

      int[] x = [42];
      const(x): /* x is const from here on */
      x[0] = 100; /* error - x is const, not head-const */

> 
>     const(outer)
> 
> allows you to check const correctness via outer instead of via this.
> That is, "I promise not to modify any member variables of an outer
> class". And so on.

Now that does sound useful.

--bb



More information about the Digitalmars-d mailing list