简体   繁体   English

如何使用shared_ptr避免内存泄漏?

[英]How to avoid memory leak with shared_ptr?

Consider the following 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;
}

There is no output . 没有输出 No desctructor is called. 没有调用desctructor 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? 如果我需要在类中进行交叉引用,我该怎么办?

If you have circular references like this, one object should hold a weak_ptr to the other, not a shared_ptr . 如果你有像这样的循环引用,一个对象应该将weak_ptr保存到另一个,而不是shared_ptr

From the shared_ptr introduction : 来自shared_ptr介绍

Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. 由于实现使用引用计数,因此不会回收shared_ptr实例的循环。 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." 例如,如果main()shared_ptr保存到A ,它直接或间接地将shared_ptr保存回A ,则A的使用计数将为2.原始shared_ptr破坏将使A悬空使用计数为1。 weak_ptr “打破周期”。

Thanks, Glen, for the link. 谢谢,格伦,链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM