在磁盘上存储/加载C ++对象

时间:2013-10-29 14:52:45

标签: c++ serialization

class MyClass
{
   private:
      AnotherClass obj;
      float d;
      int k;

    public:
      MyClass(float d = 0.3, int k = 10);
      virtual ~MyClass();
      // other methods goes here
}

是否可以使用允许此类(MyClass)保存到磁盘(硬盘驱动器)void storeOnDisk(string path){...}上的属性值的方法,以及允许从磁盘{{1}加载属性值的另一种方法}

如果可能的话,我是否也应该在MyClass的构造函数中调用void loadFromDisk(string path)(可能创建另一个构造函数),并在MyClass的析构函数中调用loadFromDisk(path),以便在退出时可以保存所有当前值实现MyClass的程序?

2 个答案:

答案 0 :(得分:2)

是的,您可以使用http://www.boost.org/doc/libs/1_34_0/libs/serialization/doc/index.html。 (你期待的更多)

答案 1 :(得分:2)

这取决于你想要达到的目标。但是,通常,你不喜欢在ctor / dtor中有这样的东西,因为在C ++" copy"和"临时对象"有时出现。 Ctors / dtors在创建/删除时会被调用,就像常规对象一样,除非您准备好 代码,否则它也会触摸文件。

通常,保持一个处理读/写的单独类会更容易一些。想象一下MyClassStorage class friend MyClass MyClass read(path),只包含两种方法:write(path MyClass&)gps_position

如果您喜欢单一课程,或者如果您不想手动完成所有操作,可以查看一些序列化框架,例如Boost :: Serialization。关于如何处理它有许多简短易行的例子,但是 - 仍然 - 你必须先阅读一下它。

编辑:

请参阅http://www.boost.org/doc/libs/1_45_0/libs/serialization/doc/tutorial.html和"一个非常简单的案例"部分。它显示了如何读/写serialize类。请注意,此类iteself非常简单,只是它包含一个额外的main函数。这个功能可以自动运行'作为读者和作家。因为通常你想要阅读你想写的相同的字段,所以不需要说两遍(而不是说read-A-B-C和write-A-B-C你说:handleThemForMe-A-B-C)。

然后,在text_oarchive中您有使用示例。 text_iarchivegps_position充当输出和输入文件。创建了一些g对象并将其命名为filename,然后将其保存到名为newg的文件中,然后将其作为ofstream从文件中读回。

实际上,// create class instance const gps_position g(35, 59, 24.567f); /// .... // save data to archive { // create and open a character archive for output std::ofstream ofs("filename"); boost::archive::text_oarchive oa(ofs); // write class instance to archive oa << g; // archive and stream closed when destructors are called } /// .... // ... some time later restore the class instance to its orginal state gps_position newg; { // create and open an archive for input std::ifstream ifs("filename"); boost::archive::text_iarchive ia(ifs); // read class state from archive ia >> newg; // archive and stream closed when destructors are called } 行太早,可能会产生误导。它只用于创建oarchive,可以像ifstream / iarchive一样安全地移动。它可能看起来像那样:

{{1}}