You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用rapidjson时如何保留被移动的child节点的有效引用?

解决方案
  • 方案1:添加节点后直接引用父节点内的元素
    AddMember执行完成后,直接通过key从parent中取出对应节点的引用持有即可,后续直接操作该引用就能修改父节点内的child节点,不需要遍历树:
rapidjson::Value parent;
parent.SetObject();

rapidjson::Value child;
child.SetObject();

parent.AddMember("child", child, document.GetAllocator());
// 直接持有parent中child节点的引用
rapidjson::Value& usableChild = parent["child"];

// 后续修改直接操作usableChild即可,改动会直接同步到JSON结构中
usableChild.AddMember("test_key", 123, document.GetAllocator());
  • 方案2:直接在父节点内创建节点,省掉临时变量
    如果不需要提前对临时child变量做操作,可以直接在父节点中初始化对应类型的节点,直接拿引用:
rapidjson::Value parent;
parent.SetObject();

// 直接在parent中创建object类型的child节点,直接拿引用
parent.AddMember("child", rapidjson::kObjectType, document.GetAllocator());
rapidjson::Value& usableChild = parent["child"];

// 后续直接操作引用即可
  • 补充方案:深拷贝避免原变量被移动
    如果你需要保留原始的child临时变量不受移动语义影响,可以做深拷贝后再添加到父节点:
rapidjson::Value parent;
parent.SetObject();

rapidjson::Value child;
child.SetObject();
// 深拷贝一个临时对象传入AddMember,原child变量不会被修改
parent.AddMember("child", child.CopyFrom(child, document.GetAllocator()), document.GetAllocator());
// 此时原child变量还可以正常使用,parent中的节点是独立的拷贝

持有rapidjson::Value的引用或指针时,需要保证对应的父节点、整个Document对象的生命周期长于你持有的引用/指针,避免出现野引用。

内容的提问来源于stack exchange,提问作者Lord Nikon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:39:04