C++ rapidjson 返回值

标签 c++ rapidjson

我在我的项目中使用 rapidjson。 我有一个方法可以解析 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();

问题是 title1 被成功读取,但 title2 在 document.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());

关于C++ rapidjson 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34313527/

相关文章:

c++ - CUDA 内核第二次运行时运行速度更快 - 为什么?

c++ - 获取嵌套的 JSON 成员而不直接获取每个中间对象

c++ - rapidjson cocos2d-x解析

c++ - 是否可以尝试在静态库中捕获断言调用(C++)

c++ - 为 OSI 第 2 层流量生成器寻找 OSS

c++ - Bulls & Cows 项目 : cow checking

c++ - 我的快速排序实现有什么问题?

C++ 在 Visual Studio 2015 中使用 Allegro5 al_init_image_addon() 错误

c++ - 通过 Boost ASIO 发送对象时断言 `IsObject()' 失败