How to avoid memory leak with shared_ptr?

后端 未结 1 1815
庸人自扰
庸人自扰 2020-11-27 04:46

Consider the following code.

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


        
相关标签:
1条回答
  • 2020-11-27 05:29

    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.

    0 讨论(0)
提交回复
热议问题