As part of a larger C++11 application, I have a function which creates a Boost JSON object
and then returns it. One of the parameters to this function is a Boost JSON storage_ptr
to an external monotonic memory resource which is used to create the object
like object myObject(sp)
. I want to avoid returning the object as a value since the object could be a large JSON structure, so I've been attempting to return it by reference.
object& getObject(storage_ptr sp)
{
// Create object with external storage_ptr
object myObject(sp);
// Modify the object
myObject["key"] = "value";
// Return reference to local object
return myObject;
}
This works, but then, understandably, I get the following compiler warning:
warning: reference to local variable 'myObject' returned
Is there a way that I can avoid returning the object by value without upsetting the compiler? I'm quite new to the custom memory resource stuff that storage_ptr
references, so I'm assuming there's a neater way to do something with that, but I can't seem to find it anywhere.
The easiest solution is just
object getObject(storage_ptr sp)
{
// Create object with external storage_ptr
object myObject(sp);
// Modify the object
myObject["key"] = "value";
// Return local object.
return myObject;
}
You're worried about a C++98 copy, but C++11 introduced move semantics, and Boost JSON supports that.
Or (untested)
object getObject(storage_ptr sp)
{
return object({{"key", "value"}}, sp);
}