My Design for Constness

Xinok xnknet at gmail.com
Wed Jun 27 14:04:56 PDT 2007


This is my own design for constness. I decided to post this because I 
feel it is simpler than what D currently offers, and is just as powerful.

I use a total of four keywords:
alias, const, final, fixed

Aliases could be used for compile time constants and CTFE:
alias al = 35;
alias string str = "String";

Const is the 'permanent' type, meaning that nothing will ever change 
it's value. It cannot be used for compile time constants, so this 
expression would be OK:
const int c = rand();

Final is the 'read only' type, meaning you cannot alter the value, but 
other functions or threads might change it's value. As with const, it 
cannot be used for compile time constants.
final int* ptr = &c;

Fixed is for reference types, including pointers, arrays, delegates, and 
classes. Fixed is not transitive like const and final, but it can be 
used similarly to C const.

class N{ int a, b; }
fixed N obj = new N;
obj.a = 35; // OK
obj = new N; // Error - 'obj' is fixed

int[] arr = [10, 20, 30];
arr[0] = 0; // OK
arr = [30, 40, 50]; // Error - 'arr' is fixed

Fixed can be used similarly to C const:
int fixed(**) ptr // int *const *const ptr


All of the keywords (alias const final fixed) keep the same meaning, 
regardless if they're local variables, global variables, class 
variables, or function parameters.

I choose not to use the 'invariant' keyword, because besides for being 9 
characters long, invariant is also used for contract programming, and I 
think there is not enough similarity between contract programming and 
constness to use invariant for both.



More information about the Digitalmars-d mailing list