我确定以前有人问过这个问题,但是对于我的具体情况,搜索词让我失望了。
本质上,我正在创建一个 2D 平铺引擎。为了整体效率并减少一些开销,我决定实现自己的简单内存管理容器......
以下代码是我用来这样做的:
Tile.h:
//Tile class
class CTile
{
public:
    CTile();
    ~CTile();
    unsigned int row;
    unsigned int column;
};
//Container class
class CTileLayer
{
public:
    CTileLayer(unsigned int nRows, unsigned int nCols, float w, float h);
    ~CTileLayer();
protected:
    CTile** m_tiles;
    unsigned long count;
    void Allocate(unsigned int nRows, unsigned int nCols, float w, float h);
    void Free();
};
Tile.cpp:
#include "Tile.h"
CTile::CTile() : row(0), column(0)
{
}
CTile::~CTile()
{
}
CTileLayer::CTileLayer(unsigned int nRows, unsigned int nCols, float w, float h) : m_tiles(NULL)
{
    Allocate(nRows, nCols, w, h);
}
CTileLayer::~CTileLayer()
{
    if(m_tiles != NULL) Free();
}
void CTileLayer::Allocate(unsigned int nRows, unsigned int nCols, float w, float h)
{
    unsigned int column = 0, row = 0;
    if(m_tiles != NULL) Free();
    m_tiles = new CTile*[count = (nRows * nCols)];
    for( unsigned long l = 0; l < count; l++ ) {
        m_tiles[l] = new CTile[count];
        m_tiles[l]->column = column + 1;
        m_tiles[l]->row = row + 1;
        //
        //...
        //
        if(++column > nCols) {
            column = 0;
            row++;
        }
    }
}
void CTileLayer::Free()
{
    delete [] *m_tiles;
    delete [] m_tiles;
    m_tiles = NULL;
    count = 0;
}
因此,通过查看每个图块是如何分配/释放的,是否可以肯定地说这不会产生任何内存泄漏?
如果可以,在确保调用每个对象的析构函数的同时释放这个数组的最合适方法是什么?我应该遍历数组,手动删除每个对象吗?