Basic dynamic array question. Use of new versus no new.

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 11 02:16:02 PDT 2014


On Wednesday, 11 June 2014 at 05:46:07 UTC, Ali Çehreli wrote:
> On 06/10/2014 08:06 PM, Matt wrote:
>
> > On Wednesday, 11 June 2014 at 02:30:01 UTC, WhatMeWorry wrote:
>
> >> int[] array; // initially empty
> >> array.length = 5; // now has 5 elements
> >>
> >> while in Mr. Alexandrescu's book, it says
> >>
> >> To create a dynamic array, use a new expression (§ 2.3.6.1
> on page 51)
> >> as follows:
> >>
> >> int[] array = new int[20]; // Create an array of 20 integers
>
> > I would have read the second as creating a static array of 20
> ints in
> > heap memory, then assigning a dynamic array to point to it.
>
> Correct but it is not different from the first one, other than 
> doing it in one step.

Wait, what? That's not correct. "new int[20]" is simply "one of 
two" syntaxes to allocate an array of 20 ints, the other being 
"new int[](20)".

It does NOT allocate a static array, and then slice it. Proof is 
that there is APPENDABLE data present, which should not happen if 
you had actually simply allocated a single element of type 
int[20] (APPENDABLE data is only present for array-style 
allocation).

AFAIK, there is no "natural" way to allocate either a static 
array or a slice itslef, using new syntax. It can be done via the 
"wrapper struct" hack though:

//----
//Used to allocate a slice "int[]".
//Or a static array "int[20]" on the heap.
struct NewWrapper(T)
{
     T data;
}
void main()
{
     int[] arr1 = new int[20];
     int[] arr2 = (new NewWrapper!(int[20])).data[];
     writeln(arr1.length);   //20, as expected
     writeln(arr1.capacity); //31 on my machine
     writeln(arr2.length);   //20
     writeln(arr2.capacity); //0
}
//----

Too bad the ambiguous syntax has us resolve to these tricks. It 
also prevents value constructing an array of elements. A syntax 
where the array sizes came *before* the type could have solved 
these issue:
int size = 20;
new size int[5]([1, 2, 3, 4, 5]);
Allocate "20" (runtime) elements of type "int[5]", each 
initialized to the value ([1, 2, 3, 4, 5]).

But, well, that ship has set sail long ago :(


More information about the Digitalmars-d-learn mailing list