【问题标题】:freeing up memory for a linked list structure containing STL classes为包含 STL 类的链表结构释放内存
【发布时间】:2014-02-13 16:46:18
【问题描述】:

我有一个由结构定义的链表

struct node {
    std::string elem;
    std::vector<node *> children;
};

假设它是正确动态分配的,那么之后如何释放堆? 我正在尝试这个:

void removeNodes(node* hElem) {
   for (node *hElemChildren: hElem->children)
       removeNodes(hElemChildren);
   delete hElem;
}

但我担心在这个过程中我会丢失动态分配给std::stringstd::vector 的内存。如果这里有内存泄漏,有人可以告诉我吗?谢谢!

【问题讨论】:

  • string 不会丢失内存,delete hElem 完全免费
  • ...警告:如果 nodes with kids 被抄袭,你就会接受粗鲁的现实。仅供参考。只要你管理得好,你会没事的。

标签: c++ linked-list dynamic-memory-allocation


【解决方案1】:

这里没有内存泄漏。当您调用 delete 时,将调用该元素的析构函数,该析构函数将为 std::string 调用析构函数,然后为 std::vector 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 2022-12-04
    • 2011-05-19
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    相关资源
    最近更新 更多