【发布时间】:2013-09-18 20:16:55
【问题描述】:
我在 C++ 中有一个 valgrind 内存泄漏。 我在 Main 函数中创建了我的类 Coordinate 的二维向量指针,并用一些随机值填充它:
vector< vector<Coordinate*> > parent_vector_coords;
parent_vector_coords.push_back(calculateCannonCoordinates(bow_x, bow_y,
stern_x, stern_y, game, 2);
现在我需要删除指针。一种方法是:
for(unsigned int i = 0; i < parent_vector_coords.size(); i++)
{
for(unsigned int index = 0; index < parent_vector_coords[i].size(); index++)
{
delete parent_vector_coords[i][index];
}
}
编辑计算CannonCoordinates:
vector<Coordinate*> calculateCannonCoordinates(int bow_x, int bow_y,
int stern_x, int stern_y, Game& game, int value)
{
vector<Coordinate*> coords;
if(bow_x == stern_x)
{
if(bow_y < stern_y)
{
for(int index = bow_y; index <= stern_y; index++)
{
coords.push_back(new Coordinate(index, bow_x));
game.getBoard()->getField()[index][bow_x].setValue(value);
}
}
else if(bow_y > stern_y)
{
for(int index = bow_y; index >= stern_y; index--)
{
coords.push_back(new Coordinate(index, bow_x));
game.getBoard()->getField()[index][bow_x].setValue(value);
}
}
}
else if(bow_y == stern_y)
{
if(bow_x < stern_x)
{
for(int index = bow_x; index <= stern_x; index++)
{
coords.push_back(new Coordinate(bow_y, index));
game.getBoard()->getField()[bow_y][index].setValue(value);
}
}
else if(bow_x > stern_x)
{
for(int index = bow_x; index >= stern_x; index--)
{
coords.push_back(new Coordinate(bow_y, index));
game.getBoard()->getField()[bow_y][index].setValue(value);
}
}
}
return coords;
}
但我仍然得到由向量引起的内存泄漏。有人知道删除指针的正确方法吗?
【问题讨论】:
-
改用智能指针
-
每次看到vector
> 为矩阵建模,我都死在里面了。使用适当的矩阵类。 -
为什么不在向量中使用
std::unique_ptr而不是原始指针? -
可能会忽略“使用智能指针”/“使用唯一指针”cmets。这些是要问自己的重要问题,但不能帮助您了解当前的问题。您发布的示例代码没有泄漏任何坐标,您正在正确删除所有内容。你确定向量本身没有泄漏吗?你在任何时候都会调用 new vector >() 吗?
-
@taocp 很好,但在这种情况下,简单地按值存储坐标是否更明智? IE。
vector< vector<Coordinate> >.