array construction without heap alloc

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Dec 22 07:10:18 PST 2007


"Frank Benoit" <keinfarbton at googlemail.com> wrote in message 
news:fkj3oe$2qcm$1 at digitalmars.com...

> I wonder why arrayliterals are allocated on the heap.

Probably to prevent otherwise very common errors like:

void foo(int x, int y)
{
    someGlobal = [x, y];
}

int[] bar(int x, int y)
{
    return [x, y];
}

i.e. escaping references to a locally-allocated array.

Before anyone says "but the compiler could detect those", what about in this 
case:

extern(C) someFunc(int* arr, int len);

void myFunc(int x, int y)
{
    auto arr = [x, y];
    someFunc(arr.ptr, arr.length);
}

The compiler knows nothing about what someFunc does and can't tell if it 
stores that array away in some global variable or something, therefore it 
can't tell if this is legal code.  (This is why side effects are bad, the FP 
programmers tell us..) 




More information about the Digitalmars-d-learn mailing list