Question Details

No question body available.

Tags

c++ pass-by-value nlohmann-json

Answers (2)

Accepted Answer Available
Accepted Answer
March 31, 2026 Score: 8 Rep: 125,672 Quality: Expert Completeness: 50%

The parse() function has to return by value. What you get back is the only instance of the internal representation of the JSON data you've parsed that exists.

It's when you then pass the value (or a sub-value) you get from parse() on to other functions that you should be careful to not copy unless you actually want a separate copy to work on. You'd usually pass a const or non-const reference to the json value instead.

Note: This is not unique to json values. The same goes for most containers with unknown size.

March 31, 2026 Score: 3 Rep: 229,934 Quality: Medium Completeness: 90%

You are not "passing object by value", but returning object.

Since C++11, there are move constructors, and since C++17, there is even guaranteed copy elision.

So no copies happen there.

It is similar for std::vector and most types.

It is pass by value, i.e. void foo(Object obj); which is to be avoided (unless you really need an implicit copy).

Alternatives contains:

  • void foo(const Object& obj) to work on the object, but cannot modify it.
  • void foo(Object& obj) to work one the object, and be able to modify it.
  • void foo(Object&& obj) to transfer ownership.