| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- //
- // not_null.hpp
- // pointer
- //
- // Created by Sam Jaffe on 9/24/15.
- //
- //
- #pragma once
- #include <memory>
- #include "pointer_fwd.hpp"
- #include "ptr_compare.hpp"
- #include "maybe_null.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(); }
- 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 )
|