【发布时间】:2017-08-21 18:39:48
【问题描述】:
使用 JsonCpp,我想在嵌入式设备上序列化具有有限堆栈资源的大对象。我发现的所有示例都使用将相互复制的堆栈对象(我猜)。我想一直减少复制 Json::Value 对象,但仍然使用集群代码——这样每个对象只需要知道如何序列化自己。我准备了一个最小的例子,它指向这个答案https://stackoverflow.com/a/42829726中描述的内存管理
但在我的示例中(最后)仍然存在不需要/想要的副本:
(*p)["a"] = *a.toJson(); // value will be copied into new instance
可以通过 JsonCpp 以某种方式避免这种情况吗?
struct itoJson
{
std::shared_ptr<Json::Value> toJson();
};
struct A: itoJson
{
int i;
std::shared_ptr<Json::Value> toJson()
{
std::shared_ptr<Json::Value> p = std::shared_ptr<Json::Value>(new Json::Value());
(*p)["i"] = i;
return p;
}
};
struct B: itoJson
{
int x;
A a;
std::shared_ptr<Json::Value> toJson()
{
std::shared_ptr<Json::Value> p = std::shared_ptr<Json::Value>(new Json::Value());
(*p)["x"] = x;
(*p)["a"] = *a.toJson(); // value will be copied into new instance
return p;
}
};
【问题讨论】:
-
你为什么使用
shared_ptrs?返回Json::Value而不是std::shared_ptr<Json::Value>,您的代码应该会变得更简单、更快。 -
假设“堆栈对象”是指具有自动存储持续时间的对象,这是错误的;这里有很多动态分配,有些在你自己的代码中。
-
@nwp 我没有得到你的评论,因为我的问题完全是关于
Json::Value@BoundaryImposition 通常我在谈到堆栈和堆对象时感觉正确,我认为我们的意思是一样的,你能给我一个提示是查找正确的术语吗? -
我想你忘了一个词,“不要复制
Json::Value”。虽然看起来Type value = create_value();形式的代码会生成副本,但编译器通常足够聪明,可以优化它,即使没有启用优化标志,并让create_value直接在其最终位置创建值。您正在使用shared_ptr禁止该优化。 -
@nwp 啊好的,我明白了,提示传递编译器优化,谢谢。
标签: c++ memory-management jsoncpp