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 链表的堆栈溢出


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01