c++ - 使用引导序列化从成员函数反序列化

标签 c++ serialization boost deserialization

我想使用 boost 序列化来序列化/反序列化类实例中的数据。这个想法是类应该封装数据,以及序列化和反序列化的细节。这适用于使用 ar << this 进行序列化,但使用 ar >> this 的可比反序列化给出编译错误

error: cannot bind non-const lvalue reference of type ‘const q*&’ to an rvalue of type ‘const q*’

以下是我的不可编译的完整工作代码 restoreit函数注释掉了。这显然是对我的真实代码的简化,但问题是一样的。如何将反序列化方法封装到我的类中?

#include <fstream>
#include <iostream>
#include <map>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>

class q
{
  public:
    q() : f_() { }
    void setup() { f_.insert(std::make_pair(18,10)); }
    int getcount() { return f_.size(); }

    void storeit(const std::string &name)
    {
      std::ofstream ofs(name);
      boost::archive::text_oarchive ar(ofs);
      ar << this;
    }
    void restoreit(const std::string &name) const
    {
      std::ifstream ifs(name);
      boost::archive::text_iarchive ia(ifs);

      // The following line gives the error: cannot bind non-const lvalue reference of type ‘const q*&’ to an rvalue of type ‘const q*’
      // ia >> this;
    }

  private:
    std::map<int,int> f_;
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
      ar & f_;
    }
};

int main(void)
{
  const std::string name = "/tmp/blah";
  q foo;
  foo.setup();
  foo.storeit(name);

  q foo2;
  // I want to use foo2.restore(name) here
  {
    std::ifstream ifs(name);
    boost::archive::text_iarchive ia(ifs);
    ia >> foo2;
  }
}

最佳答案

您需要从 restoreit 定义中删除 const。恢复时,正在修改 f_ 映射 - 您只能在非常量成员函数中执行此操作。

 void restoreit(const std::string &name)
 {
      std::ifstream ifs(name);
      boost::archive::text_iarchive ia(ifs);
      ia >> *this;
 }

关于c++ - 使用引导序列化从成员函数反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348830/

相关文章:

java - 找不到符号 ois

c++ - 获取具有相同扩展名的文件列表并处理它们

c++ - boost 元组是可变的吗?

c++ - 字符串连接期间添加的额外字符

c++ - 为什么发布版本 memset 比 visual studio 2012 中的调试版本慢?

c++ - std::vector::size() 是否比手动跟踪大小慢?

go - Go 中的 Java DataOutputStream 替代方案

c++ - C++ 中的 Lambda 将一个函数赋予另一个函数

javascript - 在 Node.js 中反序列化后将对象与其类重新关联

python - Ubuntu 12.04 上的 Boost::python 示例