resizeable arrays: T[new]

Deewiant deewiant.doesnotlike.spam at gmail.com
Sat Jun 9 08:53:19 PDT 2007


Bruno Medeiros wrote:
>   int[new] a = new int[7];
>   int[new] b = a;
>   b.length = 6;
> 
>   b[1] = 2;   // writes through to a[1]
>   b.length = 4;
>   b[1] = 3;   // writes through to a[1]
>   b.length = 10;
>   b[1] = 4;   // does not write through to a[1]
> 
> Why does this problem exist? Because, setting an array length may or may
> not create a new array, and there isn't a way to know which will happen.
> Well, in that code segment we can see when it will resize, but we can't
> know in the general case (like when we receive an array as a function
> parameter). This makes setting .length as very unsafe operation, if not
> plain *broken*.
> 

There could perhaps be an internal flag in every array, initially set to false.
It would be set in the b = a assignment, thus making it known that b is an alias
to a. Then, when b.length is modified, a new array is created and the flag is unset.

I'm not quite sure how robust this would be, but having .length changeable
without creating a new array is just too handy to give up. Otherwise, we'd have
to use realloc() to achieve the same effect.

The loss here is 1 bit of .length or 1 byte in the array struct for the flag,
and the overhead of having to check it whenever .length is modified.

Of course, the simplest solution is simply to say that modification of .length
for aliased arrays is undefined behaviour.

-- 
Remove ".doesnotlike.spam" from the mail address.



More information about the Digitalmars-d-announce mailing list