| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- //
- // not_null.hpp
- // pointer
- //
- // Created by Sam Jaffe on 9/24/15.
- //
- //
- #pragma once
- #include <memory>
- #include "maybe_null.hpp"
- #include "pointer_fwd.hpp"
- #include "ptr_compare.hpp"
- template <typename P>
- class not_null<std::weak_ptr<P>>; // A weak_ptr cannot be a not_null
- template <typename P> class not_null {
- public:
- using element_type = typename std::pointer_traits<P>::element_type;
- using pointer = element_type *;
- using reference = element_type &;
- explicit not_null(std::nullptr_t) = delete;
- explicit not_null(int) = delete;
- not_null(P const & p) : _ptr(p) { validate(); }
- not_null(P && p) : _ptr(std::move(p)) { validate(); }
- template <typename Y, typename = typename std::enable_if<
- std::is_constructible<P, Y>::value>::type>
- not_null(Y const & p) : _ptr(p) {
- validate();
- }
- template <typename Y, typename = typename std::enable_if<
- std::is_constructible<P, Y>::value>::type>
- not_null(Y && p) : _ptr(std::forward<Y>(p)) {
- validate();
- }
- not_null(not_null const &) noexcept(detail::is_nt_cc<P>::value) = default;
- not_null(not_null &&) = delete;
- template <typename Y>
- explicit operator maybe_null<Y>() const
- noexcept(detail::is_nt_c<Y, P>::value) {
- return _ptr;
- }
- template <typename Y>
- explicit operator not_null<Y>() const noexcept(detail::is_nt_c<Y, P>::value) {
- return _ptr;
- }
- not_null &
- operator=(not_null const &) noexcept(detail::is_nt_ca<P>::value) = default;
- not_null & operator=(not_null &&) = delete;
- operator bool() const noexcept { return true; }
- pointer get() const noexcept { return detail::get_ptr<P>().get(_ptr); }
- reference operator*() const noexcept { return *_ptr; }
- pointer operator->() const noexcept { return get(); }
- void reset(P const & p) { operator=(not_null(p)); }
- void reset(P && p) { operator=(not_null(std::forward(p))); }
- private:
- void validate() {
- if (get() == nullptr) {
- throw null_pointer_exception{"not_null<P> cannot be null"};
- }
- }
- P _ptr;
- };
- POINTER_TEMPLATE_COMPARE(not_null)
|