diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp index a3f13d29e..8b113dac7 100644 --- a/include/nlohmann/json.hpp +++ b/include/nlohmann/json.hpp @@ -4154,7 +4154,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // copy the values first: ilist may refer to elements of this array array_t values; - values.reserve(ilist.size()); + detail::reserve_array(values, ilist.size(), detail::priority_tag<1> {}); for (const auto& element : ilist) { values.push_back(element.moved_or_copied()); diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 639f53c1a..2a429cc78 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -30235,7 +30235,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // copy the values first: ilist may refer to elements of this array array_t values; - values.reserve(ilist.size()); + detail::reserve_array(values, ilist.size(), detail::priority_tag<1> {}); for (const auto& element : ilist) { values.push_back(element.moved_or_copied()); diff --git a/tests/src/unit-custom-array-type.cpp b/tests/src/unit-custom-array-type.cpp index 00606c6e0..7a374b612 100644 --- a/tests/src/unit-custom-array-type.cpp +++ b/tests/src/unit-custom-array-type.cpp @@ -117,6 +117,22 @@ TEST_CASE("array type without capacity()") CHECK(nested.flatten().unflatten() == nested); } + SECTION("insert(pos, initializer_list) compiles and works without reserve()") + { + // std::deque has no reserve() either; insert(pos, ilist) must not + // require it (regression test for #5656, which also covers an ilist + // that refers to elements of the array being inserted into) + deque_json j = deque_json::array(); + j.push_back("a"); + j.push_back("b"); + j.push_back("c"); + + const deque_json& cj = j; + auto it = j.insert(j.begin(), {cj[0], cj[1]}); + CHECK(*it == deque_json("a")); + CHECK(j == deque_json({"a", "b", "a", "b", "c"})); + } + SECTION("references stay valid while the array grows") { deque_json j = deque_json::array();