c++ rapidjson return value

c++ rapidjson return value

本文关键字:value return rapidjson c++      更新时间:2023-10-16

我在项目中使用rapidjson。我有一个解析json并返回部分json的方法

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;
}

然后,我用这个部分从中得到一个值。

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

问题是标题1被成功读取,但标题2在文档中的以下行面临访问违规问题。h:

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

我想知道退回部分文件的正确方式是什么。(我不想使用指针)。

感谢

要返回文档的一部分,只需返回Value的(const)引用即可。
static rapidjson::Value& getStructureInfo(std::string structureType)
{
    return d[structureType.c_str()];
}
rapidjson::Value& info = StructureManager::getStructureInfo(type);
title2=info["title"].GetString();

顺便说一句,原始代码中的问题是由于d.GetAllocator()属于局部变量d,当局部变量被破坏时,分配将变得无效。下面的解决方案应该可以修复它,但我推荐上面的解决方案,它使用引用来防止复制。

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