我在 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;
}
但是我仍然得到由向量引起的内存泄漏。有人知道删除指针的正确方法吗?