Allocating a slice object

monarch_dodra monarchdodra at gmail.com
Thu Jul 4 06:54:48 PDT 2013


On Thursday, 4 July 2013 at 13:37:52 UTC, Steven Schveighoffer 
wrote:
> On Thu, 04 Jul 2013 08:02:13 -0400, monarch_dodra 
> <monarchdodra at gmail.com> wrote:
>
>> This is a pretty stupid question, but how would you allocate 
>> an "int[]" on the heap? I'm not talking about the array, but 
>> the actual slice object. EG:
>>
>> int[]* pSlice = new int[];
>> //Error: new can only create structs,
>> //dynamic arrays or class objects, not int[]'s
>>
>> Is there a simple "idiomatic" way?
>
> Not really.  There was talk at one point of deprecating that 
> version, so you had to do new int[](5) instead of new int[5], 
> and then using new int[5] to mean new "fixed sized array of 
> size 5 on the heap", and then new int[] would mean new slice on 
> the heap.
>
> But I think there's a real lack of benefit to this, plus it 
> would be confusing to people familiar with other languages.

One advantage I see is that it is a way to allocate a fixed 
amount of objects in memory in heap, without having to add the 
Appendable info.

But that change would require changing an existing semantic, so 
fat chances of that happening now.

>> I'm currently doing it by allocating a struct that wraps one:
>>
>> struct S{int[] a;}
>> int[]* pSlice1 = cast(int[]*) new S;
>> int[]* pSlice2 = &(new S).a;
>>
>> Note: This is also a neat way to allocate a static array on 
>> the heap.
>>
>> Anybody have some better way?
>
> This should work:
>
> int[] *pSlice = (new int[][1]).ptr;
>
> -Steve

Hum... That would allocate a dynamic array of slices though 
right? There'd be the Appendable overhead for just one element...


More information about the Digitalmars-d-learn mailing list