如何避免shared_ptr的内存泄漏? [英] How to avoid memory leak with shared_ptr?

查看:851
本文介绍了如何避免shared_ptr的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code。

using boost::shared_ptr;
struct B;
struct A{
    ~A() { std::cout << "~A" << std::endl; }
    shared_ptr<B> b;    
};
struct B {
    ~B() { std::cout << "~B" << std::endl; }
    shared_ptr<A> a;
};

int main() {
    shared_ptr<A> a (new A);
    shared_ptr<B> b (new B);
    a->b = b;
    b->a = a;

    return 0;
}

有是的没有输出的。的没有desctructor 的被调用。内存泄漏。
我始终认为,智能指针有助于避免内存泄漏。

There is no output. No desctructor is called. Memory leak. I have always believed that the smart pointer helps avoid memory leaks.

我应该怎么做,如果我需要在类交叉引用?

What should I do if I need cross-references in the classes?

推荐答案

如果你有这样的循环引用,一个对象应持有<一个href=\"http://www.boost.org/doc/libs/1%5F41%5F0/libs/smart%5Fptr/weak%5Fptr.htm\"><$c$c>weak_ptr其他,而不是一个的shared_ptr

If you have circular references like this, one object should hold a weak_ptr to the other, not a shared_ptr.

的shared_ptr 介绍:

由于实现使用引用计数,的shared_ptr 实例周期不会被回收。例如,如果的main()持有的shared_ptr A ,其直接或间接持有的shared_ptr A A 的使用计数是2的销毁原始的的shared_ptr 将离开 A 与使用计数叼着1.使用的weak_ptr 中断周期。

Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. For example, if main() holds a shared_ptr to A, which directly or indirectly holds a shared_ptr back to A, A's use count will be 2. Destruction of the original shared_ptr will leave A dangling with a use count of 1. Use weak_ptr to "break cycles."

感谢,幽谷,您的链接。

这篇关于如何避免shared_ptr的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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