3

I try to pass rapidjson::Document object as function argument:

std::string json_to_string(rapidjson::Document jmsg)
{
  // Convert JSON document to string
  rapidjson::StringBuffer buffer;
  rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
  jmsg.Accept(writer);
  std::string str = buffer.GetString();
  return str;
}

If I do the function just as above, I got this error when I compile the code:

In function `rapidjson::GenericDocument, rapidjson::MemoryPoolAllocator >::GenericDocument(rapidjson::GenericDocument, rapidjson::MemoryPoolAllocator > const&)':

../../rapidjson/document.h:691: undefined reference to `rapidjson::GenericValue, rapidjson::MemoryPoolAllocator >::GenericValue(rapidjson::GenericValue, rapidjson::MemoryPoolAllocator > const&)' collect2: error: ld returned 1 exit status

The error disappears if I change the argument type from "rapidjson::Document jmsg" to "rapidjson::Document &jmsg". Use the reference is ok, however, I still want to know what's wrong with the code if I don't define it as a reference type.

Max Li
  • 551
  • 2
  • 14

1 Answers1

6

You cannot pass a Document as value, you must pass it by reference or pointer. This is because Document is not copy-able.

I suggest this function declaration in your situation:

std::string json_to_string(const rapidjson::Document& jmsg)
Milo Yip
  • 4,902
  • 2
  • 25
  • 27
  • 1
    Glad to see you on SO. ) – ArtemGr Jul 15 '14 at 06:20
  • This works like a charm! But how come pointer wouldn't work? I tried passing `rapidjson::Document *doc_ptr` to my function and it keeps complaining that `Document` is not accessible. – benjaminz Oct 07 '16 at 20:45