问题描述
我已经转换了以下链表结构
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 链表的堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)