Assigning reference to nlohmann::json object inside a function #4229
-
Hello everyone, I'm attempting to iteratively / step-wise build up a nlohmann::json object with multiple hierarchies, the following being a simple example of the final desired output:
I have tried to achieve this through two functions, one to add a new hierarchy level containing an empty object ("test in the example above), and another to write a "leaf" containing a key and a specific value ("sub-test": "value" int he example above). I'm having issues adding a new hierarchy level and retrieving a reference to it. My initial idea was to create an empty nlohmann::json object outside of the function, pass it by reference to the function, and make it reference to the newly created empty object inside the function, like so:
Where parent should hold the final desired output at the end. This didn't work, as child seemed to be a copy to parent[key], instead of holding a reference, so I would end up with parent being equal to:
and independently child being equal to:
I then tried the following, which worked, but I don't understand why the above did not:
I would be very happy to receive any feedback on my code, but most importantly on why the first solution may not be working and how I could get it to work. Could it have to do with internal nlohmann::json move semantics? Or am I missing something? Thank you very much in advance, I hope my question was clear enough. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
In your first attempt, 'child' is an object on the stack of the first, while parent[key] is constructed elsewhere (on the heap). There is no way to 'reseat' child to the location of parent[key]. There are ways to make the first way work, but they're generally ugly. The 2nd is better. Generally you prefer to return values (and especially references!) through the function return rather than through parameters. |
Beta Was this translation helpful? Give feedback.
In your first attempt, 'child' is an object on the stack of the first, while parent[key] is constructed elsewhere (on the heap). There is no way to 'reseat' child to the location of parent[key].
In your second version, child is constructed to reference that parent[key] location on the heap. Recall that a reference is essentially a pointer with the limitation that it can't be nullptr nor can it be changed to point somewhere else.
There are ways to make the first way work, but they're generally ugly. The 2nd is better. Generally you prefer to return values (and especially references!) through the function return rather than through parameters.