| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- //
- // not_null.hpp
- // pointer
- //
- // Created by Sam Jaffe on 9/24/15.
- //
- //
- #pragma once
- #include <stdexcept>
- #include <memory>
- #include "pointer_fwd.hpp"
- class null_pointer_exception : public std::invalid_argument {
- using std::invalid_argument::invalid_argument;
- };
- template <typename P> class not_null<std::weak_ptr<P>>; // A weak_ptr cannot be a not_null
- template <typename T>
- class not_null {
- public:
- using element_type = typename std::pointer_traits<T>::element_type;
- using pointer = element_type *;
- using reference = element_type &;
-
- explicit not_null(std::nullptr_t) = delete;
- explicit not_null(int) = delete;
- not_null(T p) : _ptr(p) { validate(); }
- not_null(not_null const&) = default;
- template <typename Y> not_null(not_null<Y> const& other) : _ptr(other.get()) { }
-
- not_null& operator=(std::nullptr_t) = delete;
- not_null& operator=(int) = delete;
- not_null& operator=(T ptr) { return operator=(not_null<T>(ptr)); }
- not_null& operator=(not_null const&) = default;
- template <typename Y> not_null& operator=(not_null<Y> const&other) {
- _ptr = other.get();
- return *this;
- }
-
- operator bool() const { return true; }
-
- pointer get() const { return std::addressof(operator*()); }
- reference operator*() const { return *_ptr; }
- pointer operator->() const { return get(); }
-
- bool operator==(not_null const&rhs) const { return _ptr == rhs._ptr; }
- bool operator!=(not_null const&rhs) const { return _ptr != rhs._ptr; }
- bool operator<=(not_null const&rhs) const { return _ptr <= rhs._ptr; }
- bool operator>=(not_null const&rhs) const { return _ptr >= rhs._ptr; }
- bool operator< (not_null const&rhs) const { return _ptr < rhs._ptr; }
- bool operator> (not_null const&rhs) const { return _ptr > rhs._ptr; }
- private:
- void validate() {
- if (get() == nullptr) {
- throw null_pointer_exception{"not_null<T> cannot be null"};
- }
- }
- T _ptr;
- };
|