array construction without heap alloc
Frank Benoit
keinfarbton at googlemail.com
Sat Dec 22 05:34:14 PST 2007
0ffh schrieb:
>
> I compiled this using D1 (DMD):
>
> void bar( int a, int b )
> {
> int[2] arr=[a,b];
> int brr;
> int[] crr;
> crr.length=2;
> func( arr );
> printf("%p %p\n",&arr,arr.ptr);
> printf("%p\n",&brr);
> printf("%p %p\n",&crr,crr.ptr);
> }
>
> It gives me &arr==arr.ptr, which is near &brr and &crr,
> while crr.ptr is somewhere completely different.
> I suppose that kinda proofs it. =)
> Hope it's helpful.
>
> regards, frank
Sorry, but this does a heap allocation. I forgot to mention how i detect
it. I used obj2asm to get the assembly of the object file. Using the
array literal will cause a call to the d runtime _d_arrayliteralT
function, which uses heap allocation.
On IRC "Hxal" posted a template magic solution. It goes like this:
struct StaticArray(T, size_t S){
T[S] array;
}
StaticArray!(typeof(T[0]), T.length) staticArray(T...)(T values){
StaticArray!(typeof(T[0]), T.length) x;
foreach(i,v; values)
x.array[i] = v;
return x;
}
Usage is:
void bar( int a, int b ){
func( staticArray( a, b ).array )
}
I wonder why arrayliterals are allocated on the heap.
You always have the .dup option.
More information about the Digitalmars-d-learn
mailing list