boost, shared ptr Vs weak ptr? Which to use when?

后端 未结 4 1651
星月不相逢
星月不相逢 2020-12-23 00:03

In my current project I am using boost::shared_ptr quite extensively.

Recently my fellow team mates have also started using weak_ptr. I don

4条回答
  •  再見小時候
    2020-12-23 00:34

    Use weak_ptr when the objects you create contain cyclical references, i.e. shared_ptr to an object with a shared_ptr back to yourself. This is because shared_ptr cannot handle cyclical references - when both objects go out of scope, the mutual referencing means that they are not "garbage collected", so the memory is lost and you have a memory leak. Since weak_ptr does not increase the reference count, the cyclical reference problem does not occur. This also means in general that if you just want to take a pointer to something that is reference counted and do not want to increase its reference count, then use weak_ptr.

    Otherwise, you can use shared_ptr.

    For more information, check the Boost documentation.

提交回复
热议问题