Perform a copy of Document object of rapidjson

SysDragon picture SysDragon · Mar 28, 2014 · Viewed 14.6k times · Source

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?

Answer

Ethan T picture Ethan T · Dec 15, 2015

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.