constness for arrays
David Medlock
noone at nowhere.com
Tue Jul 18 08:03:02 PDT 2006
Don Clugston wrote:
> 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.
>
Agreed , Don.
Its important to note this is two issues:
1. A readonly property of arrays.
2. Implementation of #1.
If Walter agrees on #1, I am sure he is best person to ask for advice on
#2 (at least in the case of DMD).
-DavidM
More information about the Digitalmars-d
mailing list