Why can't a weak_ptr be constructed from a unique_ptr?

前端 未结 7 2115
青春惊慌失措
青春惊慌失措 2021-01-31 13:44

If I understand correctly, a weak_ptr doesn\'t increment the reference count of the managed object, therefore it doesn\'t represent ownership. It simply lets you ac

7条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 14:03

    A shared_ptr basically has two parts:

    1. the pointed-to object
    2. the reference count object

    Once the reference count drops to zero the object (#1) is deleted.

    Now a weak_ptr needs to be able to know if an object still exists. In order to do this it has to be able to see the reference count object (#2) if it's not zero it can create a shared_ptr for the object (by incrementing the reference count). If the count is zero it will return an empty shared_ptr.

    Now consider when the reference count object (#2) can be deleted? We must wait till no shared_ptr OR weak_ptr object refer to it. For this purpose the reference count object holds two reference counts, a strong ref and a weak ref. The reference count object will only be deleted when both its counts are zero. This means that part of the memory can only be freed after all the weak references are gone (this implies a hidden disadvantage with make_shared).

    tl;dr; weak_ptr depends on a weak reference count which is part of shared_ptr, there cannot be a weak_ptr without a shared_ptr.

提交回复
热议问题