@@ -37,37 +37,46 @@ namespace std {
3737
3838
3939
40- // OptionalPtr is a template to build an optional reference (meaning a
41- // reference that can be null) from a given type.
42- // It is especially suitable for reference that are not initialized during
43- // construction, but later.
44- // Reference, if exists, can be access by operator(), among other methods.
40+ // OptionalPtr is a template to build an optional pointer from a given type.
41+ // OptionalPtr differs from a raw pointer in at least two ways:
42+ // - The absence of a pointed object is represented by std::nullopt. Dereferencing
43+ // the pointer in this case will raise a std::bad_optional_access exception, rather
44+ // than the infamous segmentation fault.
45+ // - By convention, OptionalPtr is explicitely a *non-owning pointer*.
46+ //
4547template <typename T>
4648struct OptionalPtr : public std ::optional<std::reference_wrapper<T>> {
4749 using parent = std::optional<std::reference_wrapper<T>>;
4850
4951 using parent::operator =;
5052 using parent::parent;
5153
52- T& operator *() const noexcept {
54+ const T& operator *() const {
5355 return this ->value ().get ();
5456 }
55-
56- const T* operator ->(void ) const {
57- return &this ->value ().get ();
57+ T& operator *() {
58+ return this ->value ().get ();
5859 }
59- T* operator ->(void ) {
60- return &this ->value ().get ();
60+
61+ T* operator ->(void ) const {
62+ return std::pointer_traits<T*>::pointer_to (this ->value ().get ());
6163 }
6264
63- inline bool operator ==(const OptionalPtr<T>& rhs) const {
64- if (bool (*this ) xor bool (rhs)) return false ;
65- if (!*this and !rhs) return true ;
66- return &this ->value () == &rhs.value ();
65+ inline bool operator ==(const OptionalPtr<T>& other) const {
66+ if (bool (*this ) xor bool (other)) return false ;
67+ if (!*this and !other) return true ;
68+
69+ T& lhs = this ->value ().get ();
70+ T& rhs = other.value ().get ();
71+
72+ return lhs == rhs; // Rely on underlying type operator
6773 }
68- inline bool operator ==(const T& rhs ) const {
74+ inline bool operator ==(const T& other ) const {
6975 if (not this ->has_value ()) return false ;
70- return &this ->value ().get () == &rhs;
76+
77+ T& lhs = this ->value ().get ();
78+ T& rhs = other;
79+ return lhs == rhs;
7180 }
7281
7382
0 commit comments