not_null.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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>
  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(detail::is_nt_cc<P>::value) = default;
  36. not_null(not_null &&) = delete;
  37. template <typename Y>
  38. explicit operator maybe_null<Y>() const
  39. noexcept(detail::is_nt_c<Y, P>::value) {
  40. return _ptr;
  41. }
  42. template <typename Y>
  43. explicit operator not_null<Y>() const noexcept(detail::is_nt_c<Y, P>::value) {
  44. return _ptr;
  45. }
  46. not_null &
  47. operator=(not_null const &) noexcept(detail::is_nt_ca<P>::value) = default;
  48. not_null & operator=(not_null &&) = delete;
  49. operator bool() const noexcept { return true; }
  50. pointer get() const noexcept { return detail::get_ptr<P>().get(_ptr); }
  51. reference operator*() const noexcept { return *_ptr; }
  52. pointer operator->() const noexcept { return get(); }
  53. void reset(P const & p) { operator=(not_null(p)); }
  54. void reset(P && p) { operator=(not_null(std::forward(p))); }
  55. private:
  56. void validate() {
  57. if (get() == nullptr) {
  58. throw null_pointer_exception{"not_null<P> cannot be null"};
  59. }
  60. }
  61. P _ptr;
  62. };