unique_ptr 链表的堆栈溢出

我已经转换了以下链表结构

I've converted the following linked list struct

struct node {
  node* next;
  int v;
};

进入 c++11 版本 - 不使用指针.

into a c++11 version - that is not using the pointers.

struct node {
  unique_ptr<node> next;
  int v;
};

添加、删除元素和遍历工作正常,但是当我插入大约 100 万个元素时,在调用头节点的析构函数时会出现堆栈溢出.

Adding, removing elements and traversing works fine, however when I insert roughly 1mil elements, I get a stack overflow when when the destructor of the head node is called.

我不确定我做错了什么.

I'm not sure what I'm doing wrong.

{
  node n;

  ... add 10mill elements

} <-- crash here

推荐答案

你没有做错任何事.

当您创建包含 1000 万个元素的列表时,为每个节点分配 make_unique 一切正常(当然,数据不在堆栈中,也许第一个节点除外!).

When you create your list of 10 millions elements, allocation each node with make_unique everything is fine (Of course the data is not on the stack, except perhaps the first node !).

问题是当你去掉列表的头部时:unique_ptr 将负责删除它拥有的下一个节点,它也包含一个 unique_ptr 将负责删除下一个节点......等等......

The problem is when you you get rid of the head of your list: unique_ptr will take care of the deleting the next node that it owns, which also contains a unique_ptr that will take care of deleting the next node... etc...

所以最后这 1000 万个元素会被递归删除,每次递归调用都会占用堆栈上的一些空间.

So that in the end the 10 millions elements get deleted recursively, each recursive call taking some space on the stack.

相关文章