not_null.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // not_null.hpp
  3. // pointer
  4. //
  5. // Created by Sam Jaffe on 9/24/15.
  6. //
  7. //
  8. #pragma once
  9. #include <stdexcept>
  10. #include <memory>
  11. #include "pointer_fwd.hpp"
  12. class null_pointer_exception : public std::invalid_argument {
  13. using std::invalid_argument::invalid_argument;
  14. };
  15. template <typename P> class not_null<std::weak_ptr<P>>; // A weak_ptr cannot be a not_null
  16. template <typename T>
  17. class not_null {
  18. public:
  19. using element_type = typename std::pointer_traits<T>::element_type;
  20. using pointer = element_type *;
  21. using reference = element_type &;
  22. explicit not_null(std::nullptr_t) = delete;
  23. explicit not_null(int) = delete;
  24. not_null(T p) : _ptr(p) { validate(); }
  25. not_null(not_null const&) = default;
  26. template <typename Y> not_null(not_null<Y> const& other) : _ptr(other.get()) { }
  27. not_null& operator=(std::nullptr_t) = delete;
  28. not_null& operator=(int) = delete;
  29. not_null& operator=(T ptr) { return operator=(not_null<T>(ptr)); }
  30. not_null& operator=(not_null const&) = default;
  31. template <typename Y> not_null& operator=(not_null<Y> const&other) {
  32. _ptr = other.get();
  33. return *this;
  34. }
  35. operator bool() const { return true; }
  36. pointer get() const { return std::addressof(operator*()); }
  37. reference operator*() const { return *_ptr; }
  38. pointer operator->() const { return get(); }
  39. bool operator==(not_null const&rhs) const { return _ptr == rhs._ptr; }
  40. bool operator!=(not_null const&rhs) const { return _ptr != rhs._ptr; }
  41. bool operator<=(not_null const&rhs) const { return _ptr <= rhs._ptr; }
  42. bool operator>=(not_null const&rhs) const { return _ptr >= rhs._ptr; }
  43. bool operator< (not_null const&rhs) const { return _ptr < rhs._ptr; }
  44. bool operator> (not_null const&rhs) const { return _ptr > rhs._ptr; }
  45. private:
  46. void validate() {
  47. if (get() == nullptr) {
  48. throw null_pointer_exception{"not_null<T> cannot be null"};
  49. }
  50. }
  51. T _ptr;
  52. };