From 2a03a94b6967be58c4b54b989b4210a8743359fe Mon Sep 17 00:00:00 2001 From: Marcus Holland-Moritz Date: Mon, 21 Feb 2022 10:34:43 +0100 Subject: [PATCH] Terminate in `throw_exception` when exceptions are disabled My understanding of `TL_EXPECTED_EXCEPTIONS_ENABLED` is that if exceptions are *disabled*, the code using `expected` must ensure that no attempt is ever made to throw an exception. I think the current implementation of `throw_exception` is problematic because the branch in which exceptions are disabled simply tells the compiler that this code is never reached. This is most likely not true if `throw_exception` actually gets called. Reaching e.g. a `__builtin_unreachable` is undefined behaviour. I suggest that instead of using compiler-specific builtins, the code simply calls `std::terminate`. This seems appropriate, as we pretty much have a case very similar to an uncaught exception. This also solves the problem that `__builtin_unreachable` isn't implemented by a lot of embedded compilers (which is what made me look into this code in the first place). --- include/tl/expected.hpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/include/tl/expected.hpp b/include/tl/expected.hpp index 31b130a..54676ad 100644 --- a/include/tl/expected.hpp +++ b/include/tl/expected.hpp @@ -186,13 +186,9 @@ namespace detail { template [[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E &&e) { #ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - throw std::forward(e); + throw std::forward(e); #else - #ifdef _MSC_VER - __assume(0); - #else - __builtin_unreachable(); - #endif + std::terminate(); #endif }