| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- //
- // not_null.hpp
- // pointer
- //
- // Created by Sam Jaffe on 9/24/15.
- //
- //
- #pragma once
- #include <memory>
- #include "detail/compare.hpp"
- #include "exception.hpp"
- #include "maybe_null.hpp"
- #include "pointer_fwd.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 detail::pointer_compare<not_null<P>> {
- 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(
- std::is_nothrow_copy_constructible<P>::value) = default;
- not_null(not_null &&) = delete;
- template <typename Y>
- explicit operator maybe_null<Y>() const
- noexcept(std::is_nothrow_constructible<Y, P>::value) {
- return _ptr;
- }
- template <typename Y>
- explicit operator not_null<Y>() const
- noexcept(std::is_nothrow_constructible<Y, P>::value) {
- return _ptr;
- }
- not_null & operator=(not_null const &) noexcept(
- std::is_nothrow_copy_assignable<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;
- };
|