Const correctness revisited (proposal)

Oliver Dathe o.dathe at gmx.de
Tue Mar 25 03:34:38 PDT 2008


Oliver Dathe wrote:

> 
>   T[] f(T[] t const) {
>     T sum;
>     foreach (i, ti; t) { sum+=ti; }     // ok
>     auto h = t.toHash();                // ok, invariant data operation
>     static assert (is(typeof(t)==T[])); // ok, no data operation
>     // t[2] = ...;                      // error
>     // t.length = 17;                   // error
>     return t;
>   }
>   ...
>   char[]        a, y;
>   const(char)[] b;
>   const(char[]) c;
>   ...
>   // all following three calls will succeed
>   // note: for all three returntype==typeof(y)==char[] holds
>   y=f(a);
>   y=f(b);
>   y=f(c);

Ok, the last two calls to f were evil, because you get a mutable slice 
of immutable data and therefore must not be compilable, as Walter 
pointed out before!

But you could use:

   T f(T)(T t const) { ... }

or:

   T f(return T t const) { ... } // See Walter/Andrei DConf07 p.38/39

Then you could use it as intended:

   char[]        a;
   const(char)[] b;
   const(char[]) c;
   ...
   auto ya = f(a);
   static assert (is(typeof(ya)==char[]));
   ya[17]='5';
   ...
   auto yb = f(b);
   static assert (is(typeof(yb)==const(char)[]));
   yb.length = 42;
   ...
   auto yc = f(c);
   static assert (is(typeof(yc)==const(char[]));




More information about the Digitalmars-d mailing list