c++ rapidjson return 值

c++ rapidjson return value

我在我的项目中使用 rapidjson。 我有一个方法可以解析 json 和 return 的一部分。

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();

问题是 title1 已成功读取,但 title2 在 document.h 中的以下行面临访问冲突问题:

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

我想知道 return 部分文档的正确方法是什么。 (我不想使用指针)。

谢谢

对于 returns 文档的一部分,您可以简单地 returns Value.

的(常量)引用
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());