c++ - 像这样使用 delete[] 会导致内存泄漏吗?

标签 c++ memory-management dynamic-memory-allocation

我确定之前有人问过这个问题,但搜索词无法满足我的具体情况。
本质上,我正在创建一个 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/

相关文章:

计算哈希表中字符串的个数

c - 我不需要 malloc() 这个数组吗?

c++ - 无法在动态链接库中找到过程入口点

iphone - 在 Objective C block 中执行选择器

c++ - 输入特征以检测可调用对象是否有副作用?

ios - Titanium MapView 不释放内存

c++ - 在 C++ 中为已释放的内存分配一个值

c - 从文本文件中读取所有内容 - C

c++ - MPI中点对点通信造成的死锁,使用循环从master发送给children

c++再次初始化非指针对象