共享指针解除分配. [英] Shared Pointers Deallocation.

查看:147
本文介绍了共享指针解除分配.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我只是在创建一个简单的前向链接列表,该列表使用STL的共享指针来处理动态内存.但是,我遇到了堆栈溢出错误.基本上,我有一个节点"结构,该结构具有指向另一个节点"类型的共享指针和一个用于保存用户数据的数据类型.然后,我不断将其他节点添加到此共享指针.我注意到,当共享指针开始销毁自己时,起始节点在完全销毁自身之前一直调用其内部节点析构函数,最终导致堆栈溢出.我想知道是否有人对如何消除此堆栈溢出有想法?使共享指针开始从最近添加的指针中删除将是很好的.我希望这个问题很清楚,请让我知道.

谢谢,
robNO.

Hi,

I am creating just a simple forward directional Link List, which uses STL''s Shared Pointers to handle the dynamic memory. However, I am coming across a stack overflow error. Basically I have a ''node'' structure that has a shared pointer to another ''node'' type and a data type to hold the users data. I am then continually adding other nodes to this shared pointer. I am noticing that when the Shared Pointers start to destroy themselves, the beginning node keeps calling its inner nodes destructor before completely destroying itself, which eventually results in a stack overflow. I am wondering if anyone has an idea on how to eliminate this stack overflow? It would be nice to get the Shared Pointers to start deleting from the most recently added pointer. I hope this question was clear, please let me know.

Thanks,
robNO.

推荐答案

这是一个典型的问题,主要是由于以下事实:堆大于堆栈,并且基于堆的递归结构被嵌套释放. (递归)函数调用(在您的情况下为dtor).

避免此问题的一种方法是迭代删除节点,而不是通过递归删除.


It is a typical problem mainly due to the fact that the heap is greater than the stack, and a heap-based recursive structure is deallocated with a nested (recursive) function call (the dtors, in your case).

A way to avoid this problem is delete the node iteratively, not by recursion.


class A
{
    std::shared_ptr<A> next;
public:
    ~A()
    {
       while(next)
       {
           std::shared_ptr<A> killer;
           std::swap(killer, next); //next now null, our next is in killer
           std::swap(killer->next, next) //killer->next null, its next is our next
       }   //killer destroyed, *killer deleted
    }
}


如果堆栈溢出的来源是您的自定义列表,则可以使用std::list消除堆栈溢出,除非有令人信服的理由不使用-in在那种情况下,我想您会提到它.

只要共享引用的引用计数为零,共享指针就会删除封装的指针:如果父节点删除已经删除的内存,则显然它将持有指向内存的哑指针,该指针也封装在shared :: ptr中.混合智能指针和哑指针是一件坏事.

希望对您有所帮助,
If the source of your stack overflow is your custom list, you can eliminate the stack overflow by using std::list, unless there is a compelling reason not to - in which case, I assume you would have mentioned it.

Shared pointers delete the encapsulated pointer whenever their reference count is zero: if the parent node deletes memory already deleted, apparently it holds a dumb pointer to memory that is also encapsulated in a shared::ptr. Mixing smart and dumb pointers is a bad thing.

Hope this helps,


这篇关于共享指针解除分配.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆