Use of observer_ptr

前端 未结 7 1329
自闭症患者
自闭症患者 2020-12-09 01:15

What exactly is the point of the construct std::observer_ptr in the library fundamentals technical specification V2?

It seems to me that all it does is wrap a bare <

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 01:27

    It seems from the proposal that std::observer_ptr is largely for documenting that a pointer is a non-owning reference to an object, rather than an owning reference, array, string or iterator.

    However there are a couple of other benefits to using observer_ptr over T*:

    1. A default constructed observer_ptr will always be initialized to nullptr; a regular pointer may or may not be initialized, depending on the context.
    2. observer_ptr only supports operations which make sense for a reference; this enforces correct usage:
      • operator[] is not implemented for observer_ptr, as this is an array operation.
      • Pointer arithmetic is not possible with observer_ptr, as these are iterator operations.
    3. Two observer_ptrs have strict weak ordering on all implementations, which is not guaranteed for two arbitrary pointers. This is because operator< is implemented in terms of std::less for observer_ptr (as with std::unique_ptr and std::shared_ptr).
    4. observer_ptr appears to be unsupported, which may encourage the use of safer solutions (e.g. std::any and std::variant)

提交回复
热议问题