问题描述
我想使用JsonCpp在嵌入式设备上序列化具有有限堆栈资源的大对象.我发现的所有示例都使用将相互复制的堆栈对象(我想).我想一直减少复制Json :: Value对象,但仍使用集群代码-这样每个对象只需要知道如何序列化自己即可.我准备了一个最小的示例,该示例从此答案 https://stackoverflow.com/a/42829726
With JsonCpp I want to serialize big objects with limited stack resources on an embedded device. All the examples I found are using stack objects which will be copied into each other (I guess). I want to reduce the copying the Json::Value objects all the time, but still using clustered code -- so that each object just needs to know how to serialize itself. I prepared a minimal example, which orientates to the described memory management from this answer https://stackoverflow.com/a/42829726
但是在我的示例中(最后),仍然有不需要/不需要的副本:
But in my example (in the end) there is still an not needed/wanted copy:
(*p)["a"] = *a.toJson(); // value will be copied into new instance
使用JsonCpp可以避免这种情况吗?
Can this be avoided somehow with 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;
}
};
推荐答案
JsonCpp不支持移动语义—这是问题#223 .
JsonCpp does not support move semantics — this is issue #223.
在此之前,您不能完全避免复制.
Until it does, you cannot entirely avoid copies.
但是,如果您通过摆脱不必要的动态分配和智能指针来简化代码,则也许会很幸运,并看到编译器对其进行了一些优化(通过诸如之类的机制)返回值优化).但并非全部.
However, if you make your code simple by getting rid of the needless dynamic allocation and smart pointers, you may get lucky and see your compiler optimising away some of it (via mechanisms like return value optimisation). But not all of it.
这篇关于JsonCpp堆对象处理内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!