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

时间:2019-06-11 19:19:37

标签: c++ cereal

我还找不到任何有关如何将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);

1 个答案:

答案 0 :(得分:0)

您可以执行此操作,但需要做一些额外的工作。根据存档类型的不同而不同。

对于基于文本的存档(例如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));
 }