shared_ptr and weak_ptr differences

前端 未结 5 1713
别那么骄傲
别那么骄傲 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:04

    A shared_ptr wraps a reference counting mechanism around a raw pointer. So for each instance of the shared_ptr the reference count is increased by one. If two share_ptr objects refer the eachother they will never get deleted because they will never end up with a reference count of zero.

    weak_ptr points to a shared_ptr but does not increase its reference count.This means that the underying object can still be deleted even though there is a weak_ptr reference to it.

    The way that this works is that the weak_ptr can be use to create a shared_ptr for whenever one wants to use the underlying object. If however the object has already been deleted then an empty instance of a shared_ptr is returned. Since the reference count on the underlying object is not increased with a weak_ptr reference, a circular reference will not result in the underlying object not being deleted.

提交回复
热议问题