maybe_null.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // maybe_null.hpp
  3. // pointer
  4. //
  5. // Created by Sam Jaffe on 9/24/15.
  6. //
  7. //
  8. #pragma once
  9. #include <memory>
  10. #include "pointer_fwd.hpp"
  11. #include "ptr_compare.hpp"
  12. class unchecked_pointer_exception : public std::logic_error {
  13. using std::logic_error::logic_error;
  14. };
  15. template <typename P> class maybe_null<not_null<P>>; // not permitted
  16. #if defined( DEBUG )
  17. #define set_tested( value ) tested_ = value
  18. #else
  19. #define set_tested( _ )
  20. #endif
  21. template <typename P>
  22. class maybe_null : private detail::get_ptr<P> {
  23. public:
  24. using element_type = typename std::pointer_traits<P>::element_type;
  25. using pointer = element_type *;
  26. using reference = element_type &;
  27. maybe_null() noexcept : _ptr(nullptr) {}
  28. maybe_null(P const & p) noexcept(detail::is_nt_cc<P>::value) : _ptr(p) { }
  29. maybe_null(P && p) noexcept(detail::is_nt_mc<P>::value) : _ptr(std::move(p)) { }
  30. maybe_null(maybe_null const&) noexcept(detail::is_nt_cc<P>::value) = default;
  31. maybe_null(maybe_null &&) noexcept(detail::is_nt_mc<P>::value) = default;
  32. template <typename Y>
  33. maybe_null(maybe_null<Y> const&other) noexcept(detail::is_nt_c<P, Y>::value)
  34. : _ptr(other._ptr) { set_tested(other.tested_); }
  35. maybe_null& operator=(maybe_null const&) noexcept(detail::is_nt_ca<P>::value) = default;
  36. maybe_null& operator=(maybe_null &&) noexcept(detail::is_nt_ma<P>::value) = default;
  37. operator bool() const noexcept {
  38. set_tested(true);
  39. return static_cast<bool>(_ptr);
  40. }
  41. pointer get() const noexcept(noexcept(detail::get_ptr<P>::get(_ptr))) { return detail::get_ptr<P>::get(_ptr); }
  42. pointer operator->() const /*throw(unchecked_pointer_exception)*/ {
  43. return std::addressof(operator*());
  44. }
  45. reference operator*() const /*throw(unchecked_pointer_exception)*/ {
  46. #if defined( DEBUG )
  47. if ( ! tested_ ) { throw unchecked_pointer_exception{"did not verify that pointer was non-null"}; }
  48. #endif
  49. if ( ! _ptr ) { throw null_pointer_exception{"dereferencing maybe_null in null state"}; }
  50. return *_ptr;
  51. }
  52. void reset( P const & p ) { operator=(maybe_null(p)); }
  53. void reset( P && p = P() ) { operator=(maybe_null(std::forward(p))); }
  54. private:
  55. template <typename Y> friend class maybe_null;
  56. P _ptr;
  57. #if defined( DEBUG )
  58. mutable bool tested_ = false;
  59. #endif
  60. };
  61. #undef set_tested
  62. POINTER_TEMPLATE_COMPARE( maybe_null )