我确定之前有人问过这个问题,但搜索词无法满足我的具体情况。
本质上,我正在创建一个 2D tile 引擎。为了提高整体效率并减少一些开销,我决定实现自己的简单内存管理容器...
下面的代码是我用来这样做的:
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;
}
因此,通过查看每个图 block 是如何分配/释放的,可以肯定地说这不会产生任何内存泄漏吗?
如果可以,释放这个数组的最合适方法是什么,同时确保调用每个对象的析构函数?我是否应该遍历数组,手动删除每个对象?
最佳答案
为什么不这样做:
CTile* m_tiles;
m_tiles = new CTile[nRows*nColumns];
delete[] m_tiles;
关于c++ - 像这样使用 delete[] 会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006989/