Skip to content

Assigning reference to nlohmann::json object inside a function #4229

Closed Answered by nomadwolf0
AitorMonreal asked this question in Q&A
Discussion options

You must be logged in to vote

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.

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@AitorMonreal
Comment options

@nomadwolf0
Comment options

@AitorMonreal
Comment options

@nomadwolf0
Comment options

@AitorMonreal
Comment options

Answer selected by AitorMonreal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants