我的程序内存泄漏;析构函数没有被调用吗?

Memory leaks in my program; is the destructor not getting called?

我觉得我在用头撞砖墙。

我不确定是否真的调用了析构函数。我正在使用 priority_queue 来保存一堆节点。每个节点都有一个成员 m_grid,它是一个二维结构数组。这个网格代表我在我的程序中明确使用的唯一指针。

出于某种原因,我遇到了很多泄密事件。你能帮帮我吗?

这是析构函数:

grid::~grid()
{
  for (int i = 0; i < m_width; i++)
  {
    delete[] m_grid[i];
    m_grid[i] = NULL;
  }

  delete[] m_grid;
  m_grid = NULL;
}

赋值运算符:

grid& grid::operator=(const grid& g)
{
  m_x_rad = g.m_x_rad;
  m_y_rad = g.m_y_rad;
  m_width = g.m_width;
  m_height = g.m_height;
  m_orientation = g.m_orientation;

  if (m_width != 0)
    m_grid = new cell* [m_width];

  // from left to right
  for (int i = 0; i < m_width; i++)
  {
    m_grid[i] = new cell [m_height];

    // from top to bottom
    for (int j = 0; j < m_height; j++)
    {
      m_grid[i][j].m_occupied = g.m_grid[i][j].m_occupied;
      m_grid[i][j].m_rad = g.m_grid[i][j].m_rad;
    }
  }

  return *this;
}

赋值运算符类似且符合预期。 最后,这里有一些 valgrind 输出(有很多,但都与 grid::setSize() 或 grid::operator=.

有关
==13329== 200 (40 direct, 160 indirect) bytes in 1 blocks are definitely lost in loss record 25 of 166
==13329==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13329==    by 0x4020C1: grid::operator=(grid const&) (grid.cpp:192)
==13329==    by 0x40A02E: node::operator=(node const&) (node.cpp:129)
==13329==    by 0x4075A6: __push_heap<__gnu_cxx::__normal_iterator<node*, std::vector<node> >, long int, node, __gnu_cxx::__ops::_Iter_comp_val<std::greater<node> > > (stl_heap.h:135)
==13329==    by 0x4075A6: push_heap<__gnu_cxx::__normal_iterator<node*, std::vector<node> >, std::greater<node> > (stl_heap.h:199)
==13329==    by 0x4075A6: push (stl_queue.h:502)
==13329==    by 0x4075A6: aStarGraphSearch(basic_map const&, node&, std::unordered_map<int, basic_node, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<int const, basic_node> > >&, std::priority_queue<node, std::vector<node, std::allocator<node> >, std::greater<node> >&) (main_functions.cpp:216)
==13329==    by 0x4088ED: search(int) (main_functions.cpp:706)
==13329==    by 0x401AAA: main (main.cpp:13)

我真的在这里挣扎。当我使用堆栈而不是优先队列时,我没有遇到这些问题。感谢任何帮助。

您没有删除赋值运算符中的 m_grid(及其包含的数组)。

调用赋值运算符不会首先自动调用析构函数。如果要用新内存替换它,您必须自己清理对象已经拥有的任何内存。

赋值不创建新对象;它只是修改你已经拥有的对象。