【问题标题】:C++ deleting 2 dimensional pointer vectorC++ 删除二维指针向量
【发布时间】: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&lt; vector&lt;Coordinate&gt; &gt;.

标签: c++ pointers vector


【解决方案1】:

由于还有人看这个问题,所以我决定给出答案。

似乎坐标中有另一个指针对象,自动实例化(当时忘记了)。在释放坐标之前,我没有删除该指针。这就是导致 Valgrind 内存泄漏错误的原因。

每个有类似问题的人都应该考虑在评论部分给出的建议(智能指针等)

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2013-07-02
    • 2016-05-08
    • 2020-06-24
    相关资源
    最近更新 更多