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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
