How to avoid memory leak with shared_ptr?

假装没事ソ 提交于 2019-11-26 13:07:07

问题


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


回答1:


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

From the shared_ptr introduction:

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

Thanks, Glen, for the link.



来源:https://stackoverflow.com/questions/1826902/how-to-avoid-memory-leak-with-shared-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!