【发布时间】: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<std::unique_ptr<T>>即可获得更安全、更简单的解决方案。 -
如果它们之间有任何显着差异,我会感到非常惊讶。对于编码风格,我更喜欢最后一种。
-
这里使用指针的原因是什么?在我的脑海中,我认为
std::vector<Cell>会更合适。 -
启蒙之路的第一步是忘记
new和delete和指针。
标签: c++ performance vector c++17 dynamic-memory-allocation