From 996aa06e08163aa8a53105921702c09d55d20dec Mon Sep 17 00:00:00 2001 From: Treb Connell Date: Thu, 24 Sep 2015 14:09:40 -0700 Subject: [PATCH] Fix issue #45: comparing two maybe_null_dbg's can cause fail_fast --- include/gsl.h | 2 ++ tests/maybenull_tests.cpp | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/include/gsl.h b/include/gsl.h index cf6eca5..1357d76 100644 --- a/include/gsl.h +++ b/include/gsl.h @@ -202,6 +202,8 @@ public: bool operator==(const T& rhs) const { tested_ = true; return ptr_ == rhs; } bool operator!=(const T& rhs) const { return !(*this == rhs); } + bool operator==(const maybe_null_dbg& rhs) const { tested_ = true; rhs.tested_ = true; return ptr_ == rhs.ptr_; } + bool operator!=(const maybe_null_dbg& rhs) const { return !(*this == rhs); } T get() const { fail_fast_assert(tested_); diff --git a/tests/maybenull_tests.cpp b/tests/maybenull_tests.cpp index 1fdfb78..0a9d891 100644 --- a/tests/maybenull_tests.cpp +++ b/tests/maybenull_tests.cpp @@ -189,6 +189,58 @@ SUITE(MaybeNullTests) CHECK(q.present()); CHECK(q->foo()); } + + TEST(TestMaybeNullCompare) + { + int i1 = 1; + int i2 = 2; + + maybe_null_dbg p1 = &i1; + maybe_null_dbg p1_2 = &i1; + maybe_null_dbg p2 = &i2; + + CHECK_THROW(p1.get(), fail_fast); + CHECK_THROW(p1_2.get(), fail_fast); + CHECK_THROW(p2.get(), fail_fast); + + CHECK(p1 != p2); + CHECK(!(p1 == p2)); + CHECK(p1 == p1); + CHECK(p1 == p1_2); + + // Make sure we no longer throw here + CHECK(p1.get() != nullptr); + CHECK(p1_2.get() != nullptr); + CHECK(p2.get() != nullptr); + } + + TEST(TestMaybeNullCopy) + { + int i1 = 1; + int i2 = 2; + + maybe_null_dbg p1 = &i1; + maybe_null_dbg p1_2 = &i1; + maybe_null_dbg p2 = &i2; + + CHECK(p1 != p2); + CHECK(p1 == p1_2); + + // Make sure we no longer throw here + CHECK(p1.get() != nullptr); + CHECK(p2.get() != nullptr); + + p1 = p2; + + // Make sure we now throw + CHECK_THROW(p1.get(), fail_fast); + + CHECK(p1 == p2); + CHECK(p1 != p1_2); + + // Make sure we no longer throw here + CHECK(p1.get() != nullptr); + } } int main(int, const char *[])