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

后端 未结 4 1553
星月不相逢
星月不相逢 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:35

    Shared pointers implement reference counting, weak pointers do not affect reference counting and if you don't have shared pointers to an object, only weak pointers, the object gets deleted and the weak pointers now tell you that the object has been lost.

    There are two reasons to use a weak pointer:

    1. To eliminate the cost of reference count increase / decrease; however you shouldn't do this because it is error-prone and doesn't really save much time
    2. In bookkeeping data structures, e.g. you have an index of all objects Foo that are "alive", i.e. used somewhere else, and you don't want to keep a Foo alive in the index if all the "real" uses have ended. This is the basic realistic use case for weak pointers. Of course others exist also.

    So in general, my recommendation would be to use weak pointers only when you know that you want to let the referenced objects be deleted and want to detect that. In other cases use shared pointers (reference counting), or direct pointers, esp. in method local variables when you know that the objects are not going to get deleted. Also errorprone, though, but faster than shared pointers.

    N.B. cyclical objects do not need weak pointers, you can use non-cooked, regular pointers instead in most properly constructed programs. Weak pointers less risky, though.

提交回复
热议问题