constness for arrays
xs0
xs0 at xs0.com
Tue Jul 18 09:05:52 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:
Well, actually the primary motivation is correctness*, but the whole
thing does indeed seem to benefit performance as well (well, pending
some actual tests, but it seems quite obvious).
> 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).
will probably do, as soon as I have some time (but if anyone else feels
like it, go ahead ;)
> 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.
Yup.. and it's also common to .dup just because there is no indication
at all whether it is required or not, and it's the safe thing to do..
like, if you call something like ucFirst(toLower("BIBI")) there's no
need for ucFirst to .dup (already done in toLower), but it still does as
it has no idea that is the case..
xs0
*) correctness in the sense that it becomes easier to write correct
programs, and not in the sense that the compiler would force you to do
so, at least until debugtime checking is done
More information about the Digitalmars-d
mailing list