shared_ptr and weak_ptr differences

前端 未结 5 1714
别那么骄傲
别那么骄傲 2020-12-02 04:08

I am reading Scott Meyers \"Effective C++\" book. It was mentioned that there are tr1::shared_ptr and tr1::weak_ptr act like built-in pointers, but

5条回答
  •  没有蜡笔的小新
    2020-12-02 05:11

    All the above answer are WRONG. weak_ptr is NOT used to break cyclic references, they have another purpose.

    Basically, if all shared_ptr(s) were created by make_shared() or allocate_shared() calls, you will NEVER need weak_ptr if you have no resource other than memory to manage. These functions create the shared_ptr reference counter object with the object itself, and the memory will be freed at the same time.

    The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough. This problem can be solved by using weak_ptr instead. In this case, you have to ensure the weak_ptr stored in the container is not expired before using it.

提交回复
热议问题