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

考虑以下代码.

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. 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?

推荐答案

如果你有这样的循环引用,一个对象应该持有一个 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_ptrA,它直接或间接地持有一个 shared_ptr 回到AA 的使用次数将是 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."

感谢 Glen 提供链接.

相关文章