resizeable arrays: T[new]

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Jun 4 06:43:32 PDT 2007


Walter Bright wrote:

> Now, it turns out that it is very rare for a function to legitimately 
> want to resize a buffer passed to it. So we finally hit on the idea of 
> making a resizeable array a different type, say:

An excellent suggestion. And I'm not only saying that because I have 
suggested this several times myself. :p

The dual resizable array / slice semantics of the old dynamic array have 
several subtle problems, and also considering the fact that slices and 
resizable arrays are two very different beasts that seldom need to be 
mixed makes this a welcome change. I'm glad that introducing separate 
types seems to be relatively painless.

> 
>    T[n]   a;  // static array
>    T[]    b;  // dynamic array
>    T[new] c;  // resizeable array

I'd propose a different nomenclature:

T[n]   a;  // static array
T[]    b;  // (array) slice
T[new] c;  // dynamic array

I also agree with others that there are better alternatives to "new". 
T[*] is my favorite.

> So, if our function parameter is typed as T[], we know there isn't going 
> to be any monkey business going on in that function with our other 
> slices. If it's T[new], we know we need to take a hard look at it.

It will still be a bit weird appending to or resizing a T[new] function 
argument that isn't passed by reference... Actually it will most likely 
be a bug. It would be *very* neat getting that fixed too.

In 99.9 cases of 100 where one passes a T[new] as a function argument, 
one wants the argument to be passed by reference. The remaining 0.1 
cases have obvious workarounds. So... Is there any way T[new] somehow 
could be made a reference type? Just like T[U] has become.

E.g. it would be nice if the following just worked:

void appendTo(T[new] arr, T val) { arr ~= val; }

Without the problem of the user accidentally forgetting to pass arr by 
reference.

Short version: You always want to pass ref T[new]. Forgetting ref is 
probably a bug, but is silently accepted by the compiler. Ergo, ref 
should be the default. :)

/Oskar



More information about the Digitalmars-d-announce mailing list