【问题标题】:What's the most efficient way to free the memory of pointers in a std::vector?释放 std::vector 中指针内存的最有效方法是什么?
【发布时间】:2018-12-25 11:54:23
【问题描述】:

我正在编写一个扫雷克隆,我有一个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);
}

所以,为了避免内存泄漏,我需要稍后在主类 (Game) 析构函数中使用 delete 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::unique_ptr。或者完全避免使用指针。
  • godbolt.org 尝试一下,看看你会得到什么。我希望所有这些都可以通过优化编译成相同或等效的程序集。总而言之,您只需使用std::vector&lt;std::unique_ptr&lt;T&gt;&gt; 即可获得更安全、更简单的解决方案。
  • 如果它们之间有任何显着差异,我会感到非常惊讶。对于编码风格,我更喜欢最后一种。
  • 这里使用指针的原因是什么?在我的脑海中,我认为std::vector&lt;Cell&gt; 会更合适。
  • 启蒙之路的第一步是忘记newdelete和指针。

标签: c++ performance vector c++17 dynamic-memory-allocation


【解决方案1】:

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

尝试创建一个雷区类,它是分配有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";
}

这应该打印出来:

刚刚分配的 std::vector

还活着:)

死经验

即将释放 std::vector

再见!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 2023-03-22
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2021-05-29
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多