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

前端 未结 7 2112
青春惊慌失措
青春惊慌失措 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条回答
  •  走了就别回头了
    2021-01-31 14:15

    If you think about it, a weak_ptr must refer to something other than the object itself. That's because the object can cease to exist (when there are no more strong pointers to it) and the weak_ptr still has to refer to something that contains the information that the object no longer exists.

    With a shared_ptr, that something is the thing that contains the reference count. But with a unique_ptr, there is no reference count, so there is no thing that contains the reference count, thus nothing to continue to exist when the object is gone. So there's nothing for a weak_ptr to refer to.

    There would also be no sane way to use such a weak_ptr. To use it, you'd have to have some way to guarantee that the object wasn't destroyed while you were using it. That's easy with a shared_ptr -- that's what a shared_ptr does. But how do you do that with a unique_ptr? You obviously can't have two of them, and something else must already own the object or it would have been destroyed since your pointer is weak.

提交回复
热议问题