I have a C++ AuthenticatingProxy class instance with the below method. This method creates a Response object, which is then updated with state, and then returned. Because of the internals of the Response object it cannot be copied (i.e. I cannot simply return by value).
const Response& AuthenticatingProxy::Get(const std::string& host,
const std::string& path,
const http_headers& headers)
{
static Response response;
// do the HTTP call, and set response's state here
return response;
}
Many calls can occur on this method in the AuthenticatingProxy class, so having a static variable in here is not ideal. Could someone please suggest a solution that returns a reference that is not destroyed on the function exiting? Thanks.
The nearest I've got in my research are best practices pages that mention "Return by reference, not value, where a large object is created" but I'm yet to find an example! All the examples are for references that are passed in and then returned, or for int& style references - not ones where the object instances are created within the function itself.
I think the solution may exist in having the function return response as a value, but in the calling code using a const variable to capture it. Not sure if that only works for int though - all examples I find use basic types. Any help greatly appreciated.