From e2c1831223ef40be3ca3abbc4a887f134cbbb30f Mon Sep 17 00:00:00 2001 From: shuibao Date: Mon, 10 Oct 2022 18:06:46 +0800 Subject: [PATCH] use get_to instead of get for array as inplace assignment to avoid calling constructor and losing the data --- include/nlohmann/detail/conversions/from_json.hpp | 8 ++++++-- single_include/nlohmann/json.hpp | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/include/nlohmann/detail/conversions/from_json.hpp b/include/nlohmann/detail/conversions/from_json.hpp index c6299aa0b..a898a82ab 100644 --- a/include/nlohmann/detail/conversions/from_json.hpp +++ b/include/nlohmann/detail/conversions/from_json.hpp @@ -186,7 +186,9 @@ auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines { for (std::size_t i = 0; i < N; ++i) { - arr[i] = j.at(i).template get(); + // inplace assignment to avoid calling constructor and losing the data of its members + // arr[i] = j.at(i).template get(); + j.at(i).get_to(arr[i]); } } @@ -203,7 +205,9 @@ auto from_json_array_impl(const BasicJsonType& j, std::array& arr, { for (std::size_t i = 0; i < N; ++i) { - arr[i] = j.at(i).template get(); + // inplace assignment to avoid calling constructor and losing the data of its members + // arr[i] = j.at(i).template get(); + j.at(i).get_to(arr[i]); } } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index e11f52968..1805465e9 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -4746,7 +4746,9 @@ auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines { for (std::size_t i = 0; i < N; ++i) { - arr[i] = j.at(i).template get(); + // inplace assignment to avoid calling constructor and losing the data of its members + // arr[i] = j.at(i).template get(); + j.at(i).get_to(arr[i]); } } @@ -4763,7 +4765,9 @@ auto from_json_array_impl(const BasicJsonType& j, std::array& arr, { for (std::size_t i = 0; i < N; ++i) { - arr[i] = j.at(i).template get(); + // inplace assignment to avoid calling constructor and losing the data of its members + // arr[i] = j.at(i).template get(); + j.at(i).get_to(arr[i]); } }