简体   繁体   English

对对象的二维指针数组的正确分配和取消分配

[英]Proper Allocation and Deallocation of a 2d array of Pointers to objects

Basically I am writing an RPG game which has a parent type of object called 'Piece' which represents a piece or object on the map. 基本上,我正在编写一个RPG游戏,其父类型的对象称为“ Piece”,代表地图上的一块或一个对象。 The Map class has a 2d array of pointers to these Piece objects and it is declared in the Map.h header file as: Map类具有指向这些Piece对象的2d指针数组,并且在Map.h头文件中将其声明为:

Piece *** level;

And when the map class is called with a parameter with the directory of the map to load, it loads the map file and gets its dimensions. 当使用包含要加载的地图目录的参数调用地图类时,它会加载地图文件并获取其尺寸。 It gets the height and width of the map to allocate. 它获取要分配的地图的高度和宽度。 In my level array I want to treat it like this level[x][y] where x is an x coord on the map and y is ay coord on the map. 在我的级别数组中,我想将其像此level [x] [y]一样对待,其中x是地图上的x坐标,y是地图上的ay坐标。 I have done the allocation like this: 我已经完成了这样的分配:

level = new Piece**[width];
for (int i = 0; i < width; i++)
{
    level[i] = new Piece*[height];
}   

I also initialize all elements: 我还初始化了所有元素:

for (int i = 0; i < height; i++)
    for (int k = 0; k < width; k++)
        level[k][i] = 0;

Now my game works as it should, however I have no idea how to deallocate the level array so it causes a memory leak. 现在我的游戏可以正常工作了,但是我不知道如何释放级别数组,从而导致内存泄漏。 I have tried deallocation like this: 我尝试过这样的释放:

for (int i = 0; i < height; i++)
    for (int k = 0; k < width; k++)
        if (level[k][i] != 0)
            delete level[k][i];

I have tried the above code but to no avail. 我尝试了上面的代码,但无济于事。

Please help me I do not know how to deallocate this 2d array of pointers, thanks in advance. 请帮助我,我不知道如何取消分配此2d指针数组,在此先感谢。

vector<vector<shared_ptr<Piece>>> game_map(Y, vector<shared_ptr<Piece>>(X));
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        // notice position of x and y
        game_map[Y][X] = make_shared<Piece>(); // or replace Piece with derived type
    }
}

No need to delete anything. 无需删除任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM