Perform a copy of Document object of rapidjson

别说谁变了你拦得住时间么 提交于 2019-12-18 08:15:20

问题


I'm making a class and I want to return my class inside a method. My class has a rapidjson::Document object.

You can see the previous problems here: LNK2019: "Unresolved external symbol" with rapidjson

As I discovered, rapidjson prevent you to perform any kind of copy of the Document object, and then the default copy of the class containing a Document object failed. I'm trying to define my own Copy Constructor but I need to perform a copy of the object. I saw a way to hypothetically copy the object with .Accept() method, but is returning me a lot of errors inside the rapidjson::Document class:

error C2248: 'cannot access private member declared in class `rapidjson::GenericDocument'

This is my Copy Constructor:

jsonObj::jsonObj(jsonObj& other)
{
    jsonStr = other.jsonStr;
    message = other.message;

    //doc = other.doc;
    doc.Accept(other.doc);

    validMsg = other.validMsg;
}

I found in the code of the library (line 52-54) that "Copy constructor is not permitted".

This is my class:

class jsonObj {
    string jsonStr;
    Document doc; 

public:
    jsonObj(string json);
    jsonObj(jsonObj& other);

    string getJsonStr();
};

The method:

jsonObj testOBJ()
{
    string json = "{error:null, message:None, errorMessage:MoreNone}";
    jsonObj b(json);
    return b; //It fails here if I return a nested class with a rapidjson::Document in it. Returning NULL works
}

So how to perform a copy of the Document element?


回答1:


Repository https://github.com/rjeczalik/rapidjson have the DeepCopy patch which might help you copy one document into another.




回答2:


Use the CopyFrom method on a new Document:

rapidjson::Document inDoc;    // source document
rapidjson::Document outDoc;   // destination document
outDoc.CopyFrom(inDoc, outDoc.GetAllocator());

I tested this approach and changes made to the output document had no effect on the input document. Make sure the CopyFrom method is given the output document's allocator.




回答3:


I created this method to copy document object and it works fine for me:

static void copyDocument(rapidjson::Document & newDocument, rapidjson::Document & copiedDocument) {
    rapidjson::StringBuffer strbuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
    newDocument.Accept(writer);
    std::string str = strbuf.GetString();
    copiedDocument.Parse<0>(str.c_str());
}



回答4:


must use (const) reference as return type(try to store new documents in creator class), you can't copy documents, i.e. can't return by value, since implicitly you try to use disabled copy constructor



来源:https://stackoverflow.com/questions/22707814/perform-a-copy-of-document-object-of-rapidjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!