Hole of new? (Re: Array of array)

Steven Schveighoffer schveiguy at yahoo.com
Sat Jan 7 09:18:19 PST 2012

On Mon, 02 Jan 2012 18:30:52 -0500, Timon Gehr <timon.gehr at gmx.ch> wrote:

> On 01/03/2012 12:02 AM, Mafi wrote:
>> Am 02.01.2012 23:33, schrieb Timon Gehr:
>>> On 01/02/2012 11:21 PM, RenatoL wrote:
>>>> Just curious... the answer of the compiler it's a bit unclear to
>>>> me...
>>>> T[] is a dynamic array of type T.
>>>> T[][] is a dynamic array of T[]. But this doesn't work. Why?
>>> It does work. Why do you think it does not?
>>> T[] a; // ok
>>> T[][] b; // ok
>>> auto c = new T[5]; // ok
>>> auto d = new T[][5]; // ok
>>> auto e = new T[]; // fail, nonsensical
>>> auto f = new T[][]; // fail, nonsensical
>> Here we come to an interesting point I often thought of. How do you
>> allocate a T[] itself (so you get a T[]*) or a ClassType reference (so
>> you get a ClassType*) on the heap (without casting)?
>> As far as I know it's not possible with new.
>> new T[n] is of type T[].
>> new T[]* is of type T[]**.
>> new ClassType is of type ClassType.
>> new ClassType* is of type ClassType**.
>> Is this a Hole of new?
>> Mafi
> Yes, but you can use (new T[][1]).ptr; to allocate T[] itself (and get a  
> T[]*). Maybe new T[] should be interpreted as allocating a T[] and give  
> back a T[]*.

Interesting trivia, the compiler actually transforms the following:

struct S
  int x;

auto s = new S;

into this:

auto s = (new S[1]).ptr;

Found that out when revamping the array allocation code.  It's one thing  
that still bugs me because this means s will be initialized as an  
appendable array when it doesn't have to be.


More information about the Digitalmars-d-learn mailing list