Fix json::update() with merge_objects==true error
Description
This PR fixes a crash when using update() on an ordered_json object when JSON_DIAGNOSTICS is enabled.
The Issue
When update() inserts new elements into an ordered_json object, the underlying std::vector may reallocate. This invalidates the m_parent pointers of existing children, causing assert_invariant to fail immediately because the children point to the old memory address.
The Fix
I have updated the update() function to call set_parents() after insertion operations when diagnostics are enabled. This ensures that if the container moves in memory, all children are correctly updated to point to the new parent address.
Reproduction Code
#define JSON_DIAGNOSTICS 1
#include "nlohmann/json.hpp"
#include <iostream>
int main() {
using json = nlohmann::ordered_json;
json j1 = { {"numbers", {{"one", 1}}} };
json j2 = { {"numbers", {{"two", 2}}}, {"string", "t"} };
// This triggers reallocation and assertion failure without the fix
j1.update(j2, true);
std::cout << j1.dump() << std::endl;
}
coverage: 99.176% (-0.02%) from 99.191% when pulling f7e256e0a95c45a38231fbf60ef713eaad386e2e on DanielHwangbo:issue4813 into a0e9fb1e638cfbb5b8b556b7c51eaa81977bad48 on nlohmann:develop.
🔴 Amalgamation check failed! 🔴
The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.
Maybe related: #4813
Hi nlohmann,
I have fixed the Amalgamation error and would like to request a code review again!
🔴 Amalgamation check failed! 🔴
The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.