简体   繁体   中英

c++ rapidjson return value

I'm using rapidjson in my project. I have a method which parses a json and returns part of it.

static rapidjson::Document getStructureInfo(std::string structureType)
{
    rapidjson::Document d = getStructuresInfo();

    rapidjson::Document out;
    out.CopyFrom(d[structureType.c_str()], d.GetAllocator());
    std::string title1 = out["title"].GetString();

    return out;
}

and then, I'm using that part to get a value from it.

rapidjson::Document info = StructureManager::getStructureInfo(type);
title2=info["title"].GetString();

The issue is that the title1 is read successfuly, but title2 faces an access violation issue on the following line in document.h:

bool IsString() const { return (flags_ & kStringFlag) != 0; }

I'm wondering what is the proper way to return part of a document. (I don't want to use pointers).

Thanks

To returns a part of document, you can just simply returns a (const) reference of Value .

static rapidjson::Value& getStructureInfo(std::string structureType)
{
    return d[structureType.c_str()];
}

rapidjson::Value& info = StructureManager::getStructureInfo(type);
title2=info["title"].GetString();

By the way, the problem in your original code is due to d.GetAllocator() belongs to local variable d , the allocations will become invalid when the local variable is destructed. The following should fix it, but I recommend the above solution which uses reference to prevent copying at all.

out.CopyFrom(d[structureType.c_str()], out.GetAllocator());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM