May 06, 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
May 06, 2010
On Thu, 06 May 2010 06:37:20 -0400, bearophile wrote:

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

I don't know, but it was discussed not too long ago:

http://www.digitalmars.com/d/archives/digitalmars/D/ eliminate_new_operator_paraphernalia_106108.html

In particular, note Kasumi Hanazuki's post and Andrei's response to it.

-Lars