释放 std::vector 中指针内存的最有效方法是什么?

What's the most efficient way to free the memory of pointers in a std::vector?

我正在写一个扫雷克隆,我有一个 std::vector<Cell *> minefield。我正在以这种方式创建其内容:

minefield.resize(cols * rows);
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < cols; ++j)
        minefield[j + i * cols] = new Cell(j, i);
}

因此,为了避免内存泄漏,我稍后需要 delete 主 class (Game) 析构函数中的 Cell 对象。最好(最有效)的方法是什么?

是吗:

Game::~Game() {
    for (int i = 0; i < minefield.size(); ++i)
        delete minefield[i];
}

或:

Game::~Game() {
    for (auto it = minefield.begin(); it != minefield.end(); ++it)
        delete *it;
}

或者也许:

Game::~Game() {
    for (auto & m : minefield) // I'm not sure if the '&' should be here
        delete m;
}

?

我很确定您不需要那些动态分配。您可以将单元格元素的分配和解除分配委托给 std::vector。

尝试创建一个雷区 class,它是分配有 std::vector 的线性数据的“矩阵视图”。

#include <vector>
#include <iostream>

struct cell
{
   std::size_t i, j;
   bool mine;
};

class minefield
{
public:
    minefield(int rows, int columns): cells(rows*columns), rowSize(columns)
    {
        std::cout << "just allocated std::vector\n";
    }
    virtual ~minefield()
    {
        std::cout << "about to free std::vector\n";
    }
    bool stepOn(std::size_t i, std::size_t j)
    {
        return cells.at(i*rowSize + j).mine;
    }
    void set(cell c)
    {
        cells[c.i*rowSize + c.j] = c;
    }
private:
    std::vector<cell> cells;
    int rowSize;
};


void funct() {
    minefield mf(5, 5);
    mf.set(cell{0, 0, false});
    mf.set(cell{0, 1, true});

    if (not mf.stepOn(0, 0))
    {
        std::cout << "still alive :)\n";
    }
    if (mf.stepOn(0, 1))
    {
        std::cout << "dead XP\n";
    }
}
int main()
{
    funct();
    std::cout << "bye!!\n";
}

这应该打印:

just allocated std::vector

still alive :)

dead XP

about to free std::vector

bye!!