如何在结构中序列化unique_ptr<char[]>

How to serialize unique_ptr<char[]> in struct

本文关键字:char lt gt ptr 结构 unique 序列化      更新时间:2023-10-16

我找不到任何关于如何将unique_ptr序列化为数组的文档。任何帮助都会很棒。

struct Counter{
  int index;
  unique_ptr<char []> name;
    template<class Archive>
    void serialize(Archive & archive){
        archive(index, name ); // serialize things by passing them to the archive
    }
};

如何分配。

auto buffer = std::unique_ptr<char[]>(new char[BUFFER_SIZE]);
instance.name = std::move(buffer);

你可以这样做,但它需要一些额外的工作。它因存档的类型而异。

对于基于文本的存档(例如,XMLOutputArchive/XMLInputArchiveJSONOutputArchive/JSONInputArchive (,您可以使用saveBinaryValue()/loadBinaryValue()(http://uscilab.github.io/cereal/assets/doxygen/classcereal_1_1JSONOutputArchive.html(。

下面是一个完整的示例:

#include <iostream>
#include <memory>
#include <cereal/archives/xml.hpp>
#include <cereal/cereal.hpp>
struct Counter
{
  static constexpr std::size_t BUFFER_SIZE = 12;
  int index{};
  std::unique_ptr<char[]> name;
  Counter() = default;
  Counter(int i)
    : index{i},
      name{new char[BUFFER_SIZE]}
  {}
  template<class Archive>
  void load(Archive& archive)
  {
    archive(index);
    name.reset(new char[BUFFER_SIZE]);
    archive.loadBinaryValue(name.get(), BUFFER_SIZE * sizeof(decltype(name[0])));
  }
  template<class Archive>
  void save(Archive& archive) const
  {
    archive(index);
    archive.saveBinaryValue(name.get(), BUFFER_SIZE * sizeof(decltype(name[0])));
  }
};
int main()
{
  cereal::XMLOutputArchive archive(std::cout);
  Counter c(42);
  archive(CEREAL_NVP(c));
}

如果您使用的是BinaryOutputArchive/BinaryInputArchivePortableBinaryOutputArchive/PortableBinaryInputArchive则函数将变为saveBinary()loadBinary()(http://uscilab.github.io/cereal/assets/doxygen/classcereal_1_1PortableBinaryOutputArchive.html(。

对于这些,您还可以使用 binary_data() 包装数组:

 template<class Archive>
 void save(Archive& archive) const
 {
   archive(index, cereal::binary_data(name.get(), BUFFER_SIZE));
 }