这取决于你想达到的目标。但是,通常情况下,你不希望在ctor/dtor中有这样的事情,因为有时候会在C++“副本”和“临时对象”中出现。 Ctors/dtors在被创建/移除时被调用,就像常规对象一样,除非您准备好代码以及。
通常保持一个单独的类来处理读/写有点容易。想象一下MyClassStorage class
这将是MyClass
的friend
,并且将只包含两种方法: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
函数。这个功能既可以作为读写器工作,也可以“自动地”工作。由于通常你想阅读相同的领域,所以你不需要说两遍(而不是说读-A-B-C和写-A-B-C你说:handleThemForMe-A-B-C)。
然后,在main
你有使用的例子。 text_oarchive
和text_iarchive
充当输出和输入文件。某些gps_position
对象已创建并命名为g
,然后将其保存到名为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
}
它被称为序列化。 – LihO
请看看:[序列化](http://www.parashift.com/c++-faq/serialization.html) – Pol0nium
第一个问题:是的。第二个问题,如果你喜欢,当然。但是我认为如果数据恰好可用并且您希望以某种以前的状态加载,您会想要从析构函数调用storeOnDisk以在对象状态被删除之前保存对象状态,并在构造函数中loadFromDisk。 –