From d34d796b261178b2dc709c426250d29e94c20ff8 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 13:08:31 +0100 Subject: [PATCH] Let DefaultVal's converting constructor throw DefaultVal(U&&) was unconditionally noexcept, so an exception from constructing the stored value called std::terminate. That is the case for an initializer that a validator rejects: rfl::DefaultVal>> retries = 0; Default-constructing such a struct aborted instead of throwing, and so did every rfl::json::read of it, although read_struct_with_default catches the exception to return it as an error. Make the constructor noexcept only if constructing Type from U is. Co-Authored-By: Claude Fable 5.2 --- include/rfl/DefaultVal.hpp | 3 +- .../test_default_val_throwing_initializer.cpp | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 tests/json/test_default_val_throwing_initializer.cpp diff --git a/include/rfl/DefaultVal.hpp b/include/rfl/DefaultVal.hpp index 630a3f5bd..d3c2edc4d 100644 --- a/include/rfl/DefaultVal.hpp +++ b/include/rfl/DefaultVal.hpp @@ -63,7 +63,8 @@ struct DefaultVal { /// @param _value The value to convert and store (will be moved) template requires(std::is_convertible_v) - DefaultVal(U&& _value) noexcept : value_(std::forward(_value)) {} + DefaultVal(U&& _value) noexcept(std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} /// Constructs from a DefaultVal with compatible type. /// @tparam U Type convertible to T diff --git a/tests/json/test_default_val_throwing_initializer.cpp b/tests/json/test_default_val_throwing_initializer.cpp new file mode 100644 index 000000000..4b83a05ef --- /dev/null +++ b/tests/json/test_default_val_throwing_initializer.cpp @@ -0,0 +1,41 @@ +#include + +#include +#include +#include +#include + +namespace test_default_val_throwing_initializer { + +using Positive = rfl::Validator>; + +static_assert(!std::is_nothrow_constructible_v, int>, + "Converting to a Validator can throw."); +static_assert(std::is_nothrow_constructible_v, short>); + +struct InvalidInitializer { + rfl::DefaultVal retries = 0; +}; + +struct ValidInitializer { + rfl::DefaultVal retries = 5; +}; + +TEST(json, test_default_val_throwing_initializer_throws) { + EXPECT_THROW((void)InvalidInitializer{}, std::exception); +} + +TEST(json, test_default_val_throwing_initializer_is_an_error_when_reading) { + const auto res = rfl::json::read(R"({"retries":3})"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().what(), + "Value expected to be greater than or equal to 1, but got 0."); +} + +TEST(json, test_default_val_throwing_initializer_valid_default_is_used) { + const auto res = rfl::json::read(R"({})"); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->retries.value().value(), 5); +} + +} // namespace test_default_val_throwing_initializer