Stack overflow with unique_ptr linked list(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.
这篇关于unique_ptr 链表的堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:unique_ptr 链表的堆栈溢出


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09