【发布时间】:2015-10-29 22:55:42
【问题描述】:
我需要删除以下结构
typedef struct
{
exampleList* pNext; /* pointer to next entry */
exampleList* pSublist1; /* pointer to 'sublist1' list */
exampleList* pSublist2; /* pointer to 'sublist2' list */
exampleList* pSublist3; /* pointer to 'sublist3' list */
//Other data
. . .
} exampleList;
我知道我可以使用递归来做到这一点,如下所示。
void exampleClass::delete(exampleList* sampleList)
{
if (sampleList->pNext) delete(sampleList->pNext);
if (sampleList->pSublist1) delete(sampleList->pSublist1);
if (sampleList->pSublist2) delete(sampleList->pSublist2);
if (sampleList->pSublist3) delete(sampleList->pSublist3);
//cleanup code
. . .
}
这种方法的问题是我在每个列表中有大量的项目,这可能会溢出堆栈。
还忘了提到这些列表是在共享内存中工作的,所以如果这个过程发生了什么事,我想确保我不会失去对链的跟踪。
你知道删除这个结构的最简单的替代方法吗?
【问题讨论】:
-
您正在使用 C++。停止手动管理内存。使结构成员
std::unique_ptr<exampleList>而不是exampleList*(或std::shared_ptr<exampleList>,取决于需要)。unique_ptr特别是相对于手动指针管理的开销为零,并且无需处理这种废话(您甚至可能根本不需要手写的析构函数)。 -
@MitchWheat:我认为 OP 意味着当链表很长时,所涉及的递归实际上可以耗尽堆栈(因此删除节点 1 删除节点 2 删除节点 3 ...删除节点5 亿,一路上,10-40 MB 的堆栈已用尽)。这可能是一种合理的恐惧,具体取决于用例。不知道编译器是否会有效地优化递归。
-
递归的使用取决于该方法的计算成本。在您的情况下,您正在对列表的每个对象调用 delete,您将使用 for_each 获得更好的性能。
-
exampleClass::delete。你试过编译它吗? :) -
@ShadowRanger
unique_ptr可能不会从堆栈溢出中保存此构造。
标签: c++ linked-list