Add assignment from related types

This commit is contained in:
Martin Moene 2015-09-28 07:48:39 +02:00
parent 62226021a8
commit ab825037d0
2 changed files with 26 additions and 0 deletions

View File

@ -129,6 +129,12 @@ public:
not_null<T>& operator=(std::nullptr_t) = delete; not_null<T>& operator=(std::nullptr_t) = delete;
not_null<T>& operator=(int) = delete; not_null<T>& operator=(int) = delete;
template <typename U, typename Dummy = std::enable_if_t<std::is_convertible<U, T>::value>>
not_null<T> & operator=( not_null<U> const & other )
{
ptr_ = other.get(); ensure_invariant(); return *this;
}
T get() const { T get() const {
#ifdef _MSC_VER #ifdef _MSC_VER
__assume(ptr_ != nullptr); __assume(ptr_ != nullptr);

View File

@ -86,6 +86,26 @@ SUITE(NotNullTests)
int* q = nullptr; int* q = nullptr;
CHECK_THROW(p = q, fail_fast); CHECK_THROW(p = q, fail_fast);
// Allows assignment from a not_null related pointer type.
{
MyDerived derived;
not_null<MyDerived*> p = &derived;
not_null<MyBase*> q = p;
q = p;
CHECK(q == p);
}
// Terminates assignment from related pointer types for null pointer value.
{
MyDerived* z = nullptr;
MyDerived derived;
not_null<MyBase*> p = &derived;
CHECK_THROW(p = z, fail_fast);
}
} }
} }