not_null.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 "detail/compare.hpp"
  11. #include "maybe_null.hpp"
  12. #include "pointer_fwd.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>
  16. class not_null : public detail::pointer_compare<not_null<P>> {
  17. public:
  18. using element_type = typename std::pointer_traits<P>::element_type;
  19. using pointer = element_type *;
  20. using reference = element_type &;
  21. explicit not_null(std::nullptr_t) = delete;
  22. explicit not_null(int) = delete;
  23. not_null(P const & p) : _ptr(p) { validate(); }
  24. not_null(P && p) : _ptr(std::move(p)) { validate(); }
  25. template <typename Y, typename = typename std::enable_if<
  26. std::is_constructible<P, Y>::value>::type>
  27. not_null(Y const & p) : _ptr(p) {
  28. validate();
  29. }
  30. template <typename Y, typename = typename std::enable_if<
  31. std::is_constructible<P, Y>::value>::type>
  32. not_null(Y && p) : _ptr(std::forward<Y>(p)) {
  33. validate();
  34. }
  35. not_null(not_null const &) noexcept(
  36. std::is_nothrow_copy_constructible<P>::value) = default;
  37. not_null(not_null &&) = delete;
  38. template <typename Y>
  39. explicit operator maybe_null<Y>() const
  40. noexcept(std::is_nothrow_constructible<Y, P>::value) {
  41. return _ptr;
  42. }
  43. template <typename Y>
  44. explicit operator not_null<Y>() const
  45. noexcept(std::is_nothrow_constructible<Y, P>::value) {
  46. return _ptr;
  47. }
  48. not_null & operator=(not_null const &) noexcept(
  49. std::is_nothrow_copy_assignable<P>::value) = default;
  50. not_null & operator=(not_null &&) = delete;
  51. operator bool() const noexcept { return true; }
  52. pointer get() const noexcept { return detail::get_ptr<P>().get(_ptr); }
  53. reference operator*() const noexcept { return *_ptr; }
  54. pointer operator->() const noexcept { return get(); }
  55. void reset(P const & p) { operator=(not_null(p)); }
  56. void reset(P && p) { operator=(not_null(std::forward(p))); }
  57. private:
  58. void validate() {
  59. if (get() == nullptr) {
  60. throw null_pointer_exception{"not_null<P> cannot be null"};
  61. }
  62. }
  63. P _ptr;
  64. };