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

前端 未结 7 2111
青春惊慌失措
青春惊慌失措 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:07

    Conceptually, there is nothing preventing an implementation where a weak_ptr only provides access and a unique_ptr controls the lifetime. However, there are problems with that:

    • unique_ptr doesn't use reference counting to begin with. Adding the management structure for managing the weak references would be possible, but require an additional dynamic allocation. Since unique_ptr is supposed to avoid any(!) runtime overhead over a raw pointer, that overhead is not acceptable.
    • In order to use the object referenced by a weak_ptr, you need to extract a "real" reference from it, which will first validate that the pointer is not expired first and then give you this real reference (a shared_ptr in this case). This means that you suddenly have a second reference to an object that is supposed to be uniquely owned, which is a recipe for errors. This can't be fixed by returning a mixed half-strong pointer that only temporarily delays possible destruction of the pointee, because you could just as well store that one, too, defeating the idea behind unique_ptr.

    Just wondering, what problem are you trying to solve using a weak_ptr here?

提交回复
热议问题