【问题标题】:Boost : serialization of class instances that contain pointersBoost:包含指针的类实例的序列化
【发布时间】:2014-12-11 19:02:09
【问题描述】:

如果我使用 Boost 库序列化类 Container 的实例:

class Container
{
   public:
      Block** blocks;
      int blocksNumber;
}

class Block
{
   public:
     int blockType;
     unsigned char* data;
}

然后填充所有必要的数据以获得一个完整的Container:

Container container = new Container();
container.blocksNumber=5;
Block** blocks = (Block**)malloc(sizeof(Block*)*container.blocksNumber);
blocks[0] = (Block*)malloc(sizeof(Block));
//..... Filling all the necessary data... and constructing the container

所以我的问题是:实例container的序列化格式是否包含所有分配的data?换句话说,如果我反序列化容器的序列化格式,我可以读取data的内容吗?非常感谢!

【问题讨论】:

  • 你试过了吗?无论如何,你在 c++ 中使用 malloc 和双指针做什么(---该死的---)
  • 好建议,谢谢。
  • 我和你有同样的问题,但是Boost序列化不支持双指针,太糟糕了...

标签: c++ serialization boost


【解决方案1】:

我不会浪费任何时间去思考你为什么把不安全的 C 大炮带到这里来。您正在寻找使用现代通用 C++ 库 Boost Serialization。

它应该是这样的:

struct Block {
    int blockType;
    std::vector<uint8_t> data;
};

struct Container {
    std::vector<std::vector<Block>> block_lists;
};

查看完整的工作示例:

Live On Coliru

#include <boost/serialization/vector.hpp>

class Block
{
   public:
     int blockType;
     std::vector<uint8_t> data;

   private:
       friend class boost::serialization::access;
       template <typename Ar> void serialize(Ar& ar, unsigned) {
               ar & blockType;
               ar & data;
           }
};

class Container
{
   public:
       std::vector<std::vector<Block>> block_lists;

   private:
       friend class boost::serialization::access;
       template <typename Ar> void serialize(Ar& ar, unsigned) {
               ar & block_lists;
           }
};

#include <boost/archive/text_oarchive.hpp>

int main()
{
    Container const letshavesome = {
        { // block_lists
            {
                Block { 1, { 0x11, 0x12, 0x13, 0x14 } },
                Block { 2, { 0x21, 0x22, 0x23, 0x24 } },
                Block { 3, { 0x31, 0x32, 0x33, 0x34 } },
            },
            {
                Block { 4, { 0x41, 0x42, 0x43, 0x44 } },
                Block { 5, { 0x51, 0x52, 0x53, 0x54 } },
                Block { 6, { 0x61, 0x62, 0x63, 0x64 } },
            },
        }
    };

    boost::archive::text_oarchive oa(std::cout);
    oa << letshavesome;
}

输出

22 serialization::archive 11 0 0 0 0 2 0 0 0 3 0 0 0 1 4 0 17 18 19 20 2 4 0 33 34 35 36 3 4 0 49 50 51 52 3 0 4 4 0 65 66 67 68 5 4 0 81 82 83 84 6 4 0 97 98 99 100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多