Fixed-size arrays on the heap

bearophile bearophileHUGS at lycos.com
Thu May 6 03:37:20 PDT 2010


While translating some old code I have found that allocating a fixed-size array on the heap is not allowed, do you know why?


template Arr(int N) {
    alias int[N] Arr;
}
void main() {
    auto p = new Arr!(10);
}


The compiler says:
test.d(5): Error: new can only create structs, dynamic arrays or class objects, not int[10u]'s

------------------

while this is OK, and allocates the same data on the heap:

struct Arr(int N) {
    int[N] data;
}
void main() {
    auto p = new Arr!(10);
}


Maybe it's a problem caused by conflicting syntax. This can be a way to avoid the ambiguity:

auto p = new int[10];  => static array
auto p = new int[](10);  => dynamic array

------------------

I have also tried this, with not good results:


import std.stdio: writeln;
struct Arr(int N) {
    int[N] data;
    alias data this; // Bugs Bunny
}
void main() {
    auto p = new Arr!(10);
    writeln(*p);
}


toString(int[10u]) called from ...\dmd\src\phobos\std\conv.d(245) is deprecated. Instead you may want to import std.conv and use to!string(x) instead of toString(x).
toString(int[10u]) called from ...\dmd\src\phobos\std\conv.d(262) is deprecated. Instead you may want to import std.conv and use to!string(x) instead of toString(x).
Arr!(10)(0 0 0 0 0 0 0 0 0 0)

Bye and thank you,
bearophile


More information about the Digitalmars-d-learn mailing list