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

Storing/Loading C++ objects on/from disk

本文关键字:磁盘 C++ 对象 加载 存储      更新时间:2023-10-16
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){...}上的属性值,以及另一个允许从磁盘void loadFromDisk(string path)加载属性值的方法?

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

这取决于你到底想实现什么。但是,通常,您不希望在 ctor/dtor 中包含这样的东西,因为C++有时会出现"副本"和"临时对象"。Ctors/dtors 在创建/删除时被调用,就像常规对象一样,除非您很好地准备代码,否则它也会接触文件。

通常,保留一个单独的类来处理读/写会更容易一些。想象一下,一个MyClassStorage class将是MyClassfriend,并且仅包含两种方法:MyClass read(path)write(path MyClass&)

如果你喜欢把它放在单个类中,或者你不想手动完成所有事情,你可以看看一些序列化框架,如 Boost::Serialization。关于如何处理它,有许多简短而简单的例子,但是 - 仍然 - 你必须先阅读一些关于它的信息。

编辑:

请参阅 http://www.boost.org/doc/libs/1_45_0/libs/serialization/doc/tutorial.html 和"一个非常简单的案例"部分。它展示了如何读/写gps_position类。请注意,此类 iteself 非常简单,除了它包含一个附加的 serialize 函数。此函数作为读取器和写入器"自动"工作。由于通常你想读取与你想要写入的字段相同的字段,所以没有必要说两次(而不是说read-A-B-C,WRITE-A-B-C,而是说:handleThemForMe-A-B-C)。

然后,在main您有使用示例。text_oarchivetext_iarchive充当输出和输入文件。创建某个对象并命名为g gps_position,然后保存到名为filename的文件中,然后作为newg从文件中读回。

实际上,ofstream线有点太早了,可能会产生误导。它仅用于创建 oarchive,并且可以像 ifstream/iarchive 一样安全地向下移动。它可能看起来像这样:

// 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
}

它是,你可以使用 http://www.boost.org/doc/libs/1_34_0/libs/serialization/doc/index.html。(它正在做更多你期望的事情)