not_null.hpp 2.2 KB

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