const in dmd v2.011

Derek Parnell derek at nomail.afraid.org
Wed Feb 20 15:22:42 PST 2008


//-------- BEGIN CODE EXAMPLE ------------
class C{ int val; }

void main()
{
    // 'c' is an implied const reference to a const object
   const(C) c = new C;
   const(C) d = new C;
   
   c = d; // fails "variable test.main.c cannot modify const"
   c.val = 1; // fails "Error: cannot modify const/invariant c.val"
   
    // 'cc' is a const reference to an implied const object
   const C cc = new C;
   const C dd = new C;
   
   cc = dd; // fails "variable test.main.cc cannot modify const"
   cc.val = 1; // fails "Error: cannot modify const/invariant cc.val"
   
    // 'ccc' is a mutable reference to a mutable object
         C ccc = new C;
   const C ddd = new C;
   
   ccc = ddd; // fails "Error: cannot implicitly convert expression (ddd)
of type const(C) to test.C"
   ccc.val = 1; // allowed
   ddd = ccc; // fails "variable test.main.ddd cannot modify const"
   
   // 'e' is a const value 
   const(char) e = 'a';
   const(char) f = 'b';
   
   f = e; // fails "variable test.main.f cannot modify const"
   
   // 'g' is a mutable reference to an array of const data
   const(char)[] g = "abc";
   const(char)[] h = "xyz";
   
   h = g; // Allowed!!!
   h[0] = 'A'; // fails "Error: h[0] is not mutable"
   
   // 'gg' is a const reference to an array of const data
   const const(char)[] gg = "abc";
   const const(char)[] hh = "xyz"; // fails?? " Error: hh[0] is not
mutable"
   
   hh = gg; // fails "variable test.main.hh cannot modify const"
   hh[0] = 'A'; // fails "Error: constant hh[0] is not an lvalue"???
   
   // ??? 'i' is a const reference to an array of const data ???
   const(char[]) i = "abc"; 
   const(char[]) j = "xyz"; // ?? FAILS "Error: j[0] is not mutable"
   
   j = i; // fails "variable test.main.j cannot modify const"
   j[0] = 'A'; // fails "Error: constant j[0] is not an lvalue" ????
   
}
//------------ END CODE EXAMPLE ------------


Observations:
** It appears that there is no practical difference between 'const(C) c'
and 'const C c'.

** It appears that 'const(char[])' and 'const const(char)[]' are equivalent
and also not implemented well (or the error messages are just bad).

** The addition of '[]' changes the meaning of the syntax form 'const(x)
y'. Specifically 'const(x) y' means that the bits in 'y' are immutable but
'const(x)[] y' means that the bits in 'y' are mutable.

** The current implementation of const in dmd v2.011 is definitely
confusing, and is not as regular/orthogonal as I expected it to be.

** There are some access permutations that are not possible without
deceiving the compiler. This has got to be a bad thing for maintenance
costs.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
21/02/2008 10:11:53 AM


More information about the Digitalmars-d-learn mailing list