#include <fstream>
// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class my_class;
namespace boost { namespace serialization {
template<class Archive>
inline void save_construct_data(Archive & ar, const my_class * t, const unsigned int file_version);
}}
class my_class {
private:
friend class boost::serialization::access;
template<class Archive> friend void boost::serialization::save_construct_data(Archive & ar, const my_class * t, const unsigned int file_version);
const int m_attribute; // some immutable aspect of the instance
int m_state; // mutable state of this instance
template<class Archive>
void serialize(Archive &ar, const unsigned int file_version){
ar & m_state;
}
public:
// no default construct guarentees that no invalid object
// ever exists
my_class(int attribute) :
m_attribute(attribute),
m_state(0)
{}
};
namespace boost { namespace serialization {
template<class Archive>
inline void save_construct_data(
Archive & ar, const my_class * t, const unsigned int file_version
){
// save data required to construct instance
ar << t->m_attribute;
}
template<class Archive>
inline void load_construct_data(
Archive & ar, my_class * t, const unsigned int file_version
){
// retrieve data from archive required to construct new instance
int attribute;
ar >> attribute;
// invoke inplace constructor to initialize instance of my_class
::new(t)my_class(attribute);
}
}} // namespace ...
int main() {
// create and open a character archive for output
std::ofstream ofs("filename");
// create class instance
const my_class *g = new my_class(3);
// save data to archive
{
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
my_class *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
}
return 0;
}