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

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

    No-one has mentioned the performance aspect of the problem yet, so let me throw my $0.02 in.

    weak_ptr must somehow know when the corresponding shared_ptrs have all gone out of scope and the pointed object has been deallocated and destroyed. This means that shared_ptrs need to communicate the destruction towards each weak_ptr to the same object somehow. This has a certain cost – for example, a global hash table needs to be updated, where weak_ptr gets the address from (or nullptr if the object is destroyed).

    This also involves locking in a multi-threaded environment, so it can potentially be too slow for some tasks.

    However, the goal of unique_ptr is to provide a zero-cost RAII-style abstraction class. Hence, it should not incur any other cost than that of deleteing (or delete[]ing) the dynamically allocated object. The delay imposed by doing a locked or otherwise guarded hash table access, for example, may be comparable to the cost of deallocation, however, which is not desirable in the case of unique_ptr.

提交回复
热议问题