Allocating a slice object
Maxim Fomin
maxim at maxim-fomin.ru
Thu Jul 4 06:30:51 PDT 2013
On Thursday, 4 July 2013 at 12:02:16 UTC, monarch_dodra 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?
>
> 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.
Yes. This is a good example of how D type system and memory
allocation type are different, despite many move type system
terms into memory category.
> Anybody have some better way?
Another way:
import std.stdio;
void main()
{
int[] arr;
auto x = { return arr; } ;
writeln(&arr);
}
More information about the Digitalmars-d-learn
mailing list