diff --git a/test/unit.cpp b/test/unit.cpp index 9b735108d2..af52e17515 100644 --- a/test/unit.cpp +++ b/test/unit.cpp @@ -13993,3 +13993,34 @@ TEST_CASE("regression tests") CHECK(dest == expected); } } + +// special test case to check if memory is leaked if constructor throws + +template +struct my_allocator : std::allocator +{ + template + void construct(T*, Args&& ...) + { + throw std::bad_alloc(); + } +}; + +TEST_CASE("bad_alloc") +{ + SECTION("bad_alloc") + { + // create JSON type using the throwing allocator + using my_json = nlohmann::basic_json; + + // creating an object should throw + CHECK_THROWS_AS(my_json j(my_json::value_t::object), std::bad_alloc); + } +}