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

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

    It may be useful to distinguish reasons for preferring a unique_ptr over a shared_ptr.

    Performance One obvious reason is computational-time and memory use. As currently defined, shared_ptr objects typically need something like a reference-count value, which takes space and also must be actively maintained. unique_ptr objects don't.

    Semantics With a unique_ptr, you as the programmer have a pretty good idea when the pointed-to object is going to be destroyed: when the unique_ptr is destroyed or when one of its modifying methods is called. And so on large or unfamiliar code bases, using unique_ptr statically conveys (and enforces) some information about the program's runtime behavior that might not be obvious.

    The comments above have generally focused on the performance-based reasons that it would be undesirable for weak_ptr objects to be tied to unique_ptr objects. But one might wonder if the semantics-based argument is sufficient reason for some future version of the STL to support the use-case implied by the original question.

提交回复
热议问题