proposal: capacity variable for dynamic arrays

Kevin Bealer Kevin_member at pathlink.com
Tue Jul 18 13:10:57 PDT 2006


In article <e8udip$2c0r$1 at digitaldaemon.com>, Ameer Armaly says...
>
>
>"Lionello Lunesu" <lionello at lunesu.remove.com> wrote in message 
>news:e8u973$21uo$1 at digitaldaemon.com...
>> What's the capacity of a slice?
>>
>The capacity of a slice is strictly the number of elements in that slice; 
>any expansion in capacity would result in a new memmory block.

An alternate solution would be to use 0 for the capacity of slices; then allow
people to downsize slice objects, but as soon as they increase them,
reallocation is triggered.

My rationale is the following scenario:

char[] b = /* something */;
char[] a = b[0..10]; // 10 bytes

a.resize(5);
a.resize(10);

If slice capacity is the same as length, the slice gets smaller, and when it
gets larger, a[5..10] is initialized, BUT so is b[5..10].  If the capacity were
left at zero for the slice, the second resize would reallocate rather than
corrupting the contents of B.

This also provides a handy way of checking if an array is a slice.

>> Futhermore, the capacity can't be stored in the memory block, since you 
>> don't know the start and end of the block. Could be stored in the array 
>> variables itself (as are length and ptr), but that would make the 
>> sizeof(array) and strange 12, probably being padded to 16, resulting in 
>> twice the mem transfer for array arguments, return values.
>>
>> L.

Since most systems will be 64 bit soon, I think this padding could be avoided
most of the time -- you rarely want padding to more than 8 bytes.  Of course, an
array of arrays has the unfortunate "multiply by 24" when indexing (i.e.
multiply by a non-power of two, which is slower than shifting.)

Kevin





More information about the Digitalmars-d mailing list