为了说明这个问题,假设我们要序列化一个包含共享指针(
std::shared_ptr
)的类,以及一个静态
load
函数,它将从一个文件构建这个类,以及一个将实例存储到一个文件中的
save
函数:
代码语言:
javascript
复制
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <fstream>
#include <memory>
#include <vector>
class A
public:
std::shared_ptr<int> v;
void A::Save(char * const filename);
static A * const Load(char * const filename);
//////////////////////////////////
// Boost Serialization:
private:
friend class boost::serialization::access;
template<class Archive> void serialize(Archive & ar, const unsigned int file_version)
ar & v;
// save the world to a file:
void A::Save(char * const filename)
// create and open a character archive for output
std::ofstream ofs(filename);
// save data to archive
boost::archive::text_oarchive oa(ofs);
// write the pointer to file
oa << this;
// load world from file
A * const A::Load(char * const filename)
A * a;
// create and open an archive for input
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
// read class pointer from archive
ia >> a;
return a;