From ab825037d0b45f23ede61f600652da38defbc99d Mon Sep 17 00:00:00 2001 From: Martin Moene Date: Mon, 28 Sep 2015 07:48:39 +0200 Subject: [PATCH] Add assignment from related types --- include/gsl.h | 6 ++++++ tests/notnull_tests.cpp | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/include/gsl.h b/include/gsl.h index fed3b6c..dc4d425 100644 --- a/include/gsl.h +++ b/include/gsl.h @@ -129,6 +129,12 @@ public: not_null& operator=(std::nullptr_t) = delete; not_null& operator=(int) = delete; + template ::value>> + not_null & operator=( not_null const & other ) + { + ptr_ = other.get(); ensure_invariant(); return *this; + } + T get() const { #ifdef _MSC_VER __assume(ptr_ != nullptr); diff --git a/tests/notnull_tests.cpp b/tests/notnull_tests.cpp index 7232840..69aebaa 100644 --- a/tests/notnull_tests.cpp +++ b/tests/notnull_tests.cpp @@ -86,6 +86,26 @@ SUITE(NotNullTests) int* q = nullptr; CHECK_THROW(p = q, fail_fast); + + // Allows assignment from a not_null related pointer type. + { + MyDerived derived; + not_null p = &derived; + not_null q = p; + + q = p; + + CHECK(q == p); + } + + // Terminates assignment from related pointer types for null pointer value. + { + MyDerived* z = nullptr; + MyDerived derived; + not_null p = &derived; + + CHECK_THROW(p = z, fail_fast); + } } }