| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- //
- // not_null.hpp
- // pointer
- //
- // Created by Sam Jaffe on 9/24/15.
- //
- //
- #pragma once
- #include <stdexcept>
- #include <memory>
- #include "pointer_fwd.hpp"
- #include "ptr_compare.hpp"
- #include "maybe_null.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 const & p) : _ptr(p) { validate(); }
- not_null(T && p) : _ptr(std::move(p)) { validate(); }
- not_null(not_null const&) = default;
- template <typename Y>
- explicit operator maybe_null<Y>() const {
- return _ptr;
- }
- template <typename Y>
- explicit operator not_null<Y>() const {
- return _ptr;
- }
- not_null& operator=(not_null const&) = default;
- template <typename Y> not_null& operator=(not_null<Y> const&other) {
- _ptr = other._ptr;
- return *this;
- }
-
- explicit operator maybe_null<T>() const;
- operator bool() const { return true; }
-
- pointer get() const { return std::addressof(operator*()); }
- reference operator*() const { return *_ptr; }
- pointer operator->() const { return get(); }
-
- private:
- void validate() {
- if (get() == nullptr) {
- throw null_pointer_exception{"not_null<T> cannot be null"};
- }
- }
- T _ptr;
- };
- POINTER_TEMPLATE_COMPARE( not_null )
|