constness for arrays

Don Clugston dac at nospam.com.au
Tue Jul 18 07:23:45 PDT 2006


xs0 wrote:
> As has been discussed, the lack of something like C++ const hurts most 
> when using arrays, as you can't code around it like with classes, 
> structs or primitives (with the latter two you can just pass by value, 
> for classes you can make readonly versions). The fact that inbuilt 
> strings are also arrays makes the problem occur often.
> 
> I was wondering whether the following would resolve that issue:
> 
> - the top bit of arrays' .length becomes an indicator of the 
> readonlyness of the array reference

This is a really interesting idea. You're essentially chasing a 
performance benefit, rather than program correctness. Some benchmarks 
ought to be able to tell you if the performance benefit is real:

instead of char[], use

struct CharArray {
  char [] arr;
  bool readOnly;
}

for both the existing and proposed behaviour (for the existing one, 
readonly is ignored, but include it to make the parameter passing fair).

For code that makes heavy use of COW, I suspect that the benefit could 
be considerable. You probably don't need to eliminate many .dups to pay 
for the slightly slower .length.

The situation where a function only occasionally returns a read-only 
string is probably quite common:

char [] func(int n) {
   if (n==0) return "annoying";
   else return toString(n);
}
.. and you have to .dup it for the rare case where it's a literal.




More information about the Digitalmars-d mailing list