not_null.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // not_null.hpp
  3. // pointer
  4. //
  5. // Created by Sam Jaffe on 9/24/15.
  6. //
  7. //
  8. #pragma once
  9. #include <memory>
  10. #include "maybe_null.hpp"
  11. #include "pointer_fwd.hpp"
  12. #include "ptr_compare.hpp"
  13. template <typename P>
  14. class not_null<std::weak_ptr<P>>; // A weak_ptr cannot be a not_null
  15. template <typename P> class not_null {
  16. public:
  17. using element_type = typename std::pointer_traits<P>::element_type;
  18. using pointer = element_type *;
  19. using reference = element_type &;
  20. explicit not_null(std::nullptr_t) = delete;
  21. explicit not_null(int) = delete;
  22. not_null(P const & p) : _ptr(p) { validate(); }
  23. not_null(P && p) : _ptr(std::move(p)) { validate(); }
  24. template <typename Y, typename = typename std::enable_if<
  25. std::is_constructible<P, Y>::value>::type>
  26. not_null(Y const & p) : _ptr(p) {
  27. validate();
  28. }
  29. template <typename Y, typename = typename std::enable_if<
  30. std::is_constructible<P, Y>::value>::type>
  31. not_null(Y && p) : _ptr(std::forward<Y>(p)) {
  32. validate();
  33. }
  34. not_null(not_null const &) noexcept(detail::is_nt_cc<P>::value) = default;
  35. not_null(not_null &&) = delete;
  36. template <typename Y>
  37. explicit operator maybe_null<Y>() const
  38. noexcept(detail::is_nt_c<Y, P>::value) {
  39. return _ptr;
  40. }
  41. template <typename Y>
  42. explicit operator not_null<Y>() const noexcept(detail::is_nt_c<Y, P>::value) {
  43. return _ptr;
  44. }
  45. not_null &
  46. operator=(not_null const &) noexcept(detail::is_nt_ca<P>::value) = default;
  47. not_null & operator=(not_null &&) = delete;
  48. operator bool() const noexcept { return true; }
  49. pointer get() const noexcept { return detail::get_ptr<P>().get(_ptr); }
  50. reference operator*() const noexcept { return *_ptr; }
  51. pointer operator->() const noexcept { return get(); }
  52. void reset(P const & p) { operator=(not_null(p)); }
  53. void reset(P && p) { operator=(not_null(std::forward(p))); }
  54. private:
  55. void validate() {
  56. if (get() == nullptr) {
  57. throw null_pointer_exception{"not_null<P> cannot be null"};
  58. }
  59. }
  60. P _ptr;
  61. };
  62. POINTER_TEMPLATE_COMPARE(not_null)