JsonCpp heap object handling memory management

2019-08-26 06:22发布

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

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;
        }
    };

1条回答
▲ chillily
2楼-- · 2019-08-26 07:10

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.

查看更多
登录 后发表回答