D language: initializing dynamic multidimensional array best practices?

自作多情 提交于 2019-12-05 03:30:39

You can new the array, at least in D2:

Tile[][] tiles = new Tile[][](height, width);

I believe this is the best practice.

you can fudge it by mallocing every thing you need upfront

this(uint width, uint height) {
    void* p = enforce(GC.malloc(Tile.sizeof*width*height),new OutOfMemoryException);
          //allocate all rows at once, throw on returned null
    tiles.length = height;
    foreach (i,ref tilerow; tiles)
        tilerow = cast(Tile[])p[Tile.sizeof*width*i..Tile.sizeof*width*(i+1)];
                //slice it into the multidimensional array
}

EDIT or use a temporary array to keep hem in for cleaner/less bugprone code (i.e. hide the malloc)

this(uint width, uint height) {
    Tile[] p = new Tile[height*width]
    tiles.length = height;
    foreach (i,ref tilerow; tiles)
        tilerow = p[width*i..width*(i+1)];
                //slice it into the multidimensional array
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!