From 22e8caf3c6a8429303e447a9988b094accbbbb30 Mon Sep 17 00:00:00 2001 From: Tom Jackson Date: Thu, 16 Jul 2015 13:59:07 -0700 Subject: [PATCH 1/1] Making Optional throw exceptions instead of assert Summary: I'm upgrading assertions to throws, since these are fatal in all circumstances. If something is explicitly `Optional`, it makes sense to fail loudly if it is misused in this manner. Reviewed By: @yfeldblum Differential Revision: D2247612 --- folly/Optional.h | 25 ++++++++++++++++++++----- folly/test/OptionalTest.cpp | 5 +++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/folly/Optional.h b/folly/Optional.h index f4bc9ff4..9947fd4a 100644 --- a/folly/Optional.h +++ b/folly/Optional.h @@ -54,8 +54,8 @@ * cout << *v << endl; * } */ -#include #include +#include #include #include @@ -82,6 +82,12 @@ const None none = nullptr; # pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif // __GNUC__ +class OptionalEmptyException : public std::runtime_error { + public: + OptionalEmptyException() + : std::runtime_error("Empty Optional cannot be unwrapped") {} +}; + template class Optional { public: @@ -206,15 +212,18 @@ class Optional { } const Value& value() const { - assert(hasValue()); + require_value(); return value_; } Value& value() { - assert(hasValue()); + require_value(); return value_; } + Value* get_pointer() { return hasValue_ ? &value_ : nullptr; } + const Value* get_pointer() const { return hasValue_ ? &value_ : nullptr; } + bool hasValue() const { return hasValue_; } explicit operator bool() const { @@ -239,6 +248,12 @@ class Optional { } private: + void require_value() const { + if (!hasValue_) { + throw OptionalEmptyException(); + } + } + template void construct(Args&&... args) { const void* ptr = &value_; @@ -258,12 +273,12 @@ class Optional { template const T* get_pointer(const Optional& opt) { - return opt ? &opt.value() : nullptr; + return opt.get_pointer(); } template T* get_pointer(Optional& opt) { - return opt ? &opt.value() : nullptr; + return opt.get_pointer(); } template diff --git a/folly/test/OptionalTest.cpp b/folly/test/OptionalTest.cpp index 2cfef6c5..72c27345 100644 --- a/folly/test/OptionalTest.cpp +++ b/folly/test/OptionalTest.cpp @@ -497,4 +497,9 @@ TEST(Optional, AssignmentContained) { } } +TEST(Optional, Exceptions) { + Optional empty; + EXPECT_THROW(empty.value(), OptionalEmptyException); +} + } -- 2.34.1