rapidjson对象作为函数参数导致编译器错误

Max*_* Li 3 reference rapidjson

我尝试将rapidjson :: Document对象作为函数参数传递:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我像上面那样执行该功能,则在编译代码时出现此错误:

在函数`rapidjson :: GenericDocument,rapidjson :: MemoryPoolAllocator> :: GenericDocument(rapidjson :: GenericDocument,rapidjson :: MemoryPoolAllocator> const&)':

../../rapidjson/document.h:691:未定义引用`rapidjson :: GenericValue,rapidjson :: MemoryPoolAllocator> :: GenericValue(rapidjson :: GenericValue,rapidjson :: MemoryPoolAllocator> const&)'collect2:error:ld返回1退出状态

如果我将参数类型从"rapidjson :: Document jmsg"更改为"rapidjson :: Document&jmsg",则错误消失.使用引用是好的,但是,如果我没有将它定义为引用类型,我仍然想知道代码有什么问题.

Mil*_*Yip 6

您不能传递Documentas值,您必须通过引用或指针传递它.这是因为Document不可复制.

我建议在你的情况下这个函数声明:

std::string json_to_string(const rapidjson::Document& jmsg)
Run Code Online (Sandbox Code Playgroud)