constness for arrays

xs0 xs0 at xs0.com
Tue Jul 18 06:29:47 PDT 2006


David Medlock 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
>>
> <snip>
> 
> I like it except it drops the max array size by half, doesn't it?

Theoretically, but in practice:
- if you have a 64-bit machine, you don't care
- if you have a 32-bit machine, you can't get the full 4GB anyway (on 
Windows, a process can only allocate 2GB, I bet it's similar in other OSes)
- with anything larger than a byte you don't even theoretically need 
that bit

> Since we are talking about dynamic arrays here, why not just:
> 
> 1. add a flags byte or short to the internal array structure to hold it.

because that would increase the size of array structure, making it 
consume more memory (I'd guess at least 4 bytes per reference) and 
slower (more data to copy)

> 2. make the pointers lower bit hold it- this of course assumes the 
> pointer is at least word-aligned.  I am not sure if this would conflict 
> with structs which are align(1).

that wouldn't work - the pointer is unrestricted and can point anywhere..


xs0



More information about the Digitalmars-d mailing list