Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ rapidjson return value

Tags:

c++

rapidjson

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

like image 732
Hamed Afshar Avatar asked Sep 18 '25 15:09

Hamed Afshar


1 Answers

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());
like image 184
Milo Yip Avatar answered Sep 21 '25 06:09

Milo Yip