Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <fstream>
  2.  
  3. // include headers that implement a archive in simple text format
  4. #include <boost/archive/text_oarchive.hpp>
  5. #include <boost/archive/text_iarchive.hpp>
  6.  
  7. class my_class;
  8. namespace boost { namespace serialization {
  9. template<class Archive>
  10. inline void save_construct_data(Archive & ar, const my_class * t, const unsigned int file_version);
  11. }}
  12.  
  13. class my_class {
  14. private:
  15.     friend class boost::serialization::access;
  16.     template<class Archive> friend void boost::serialization::save_construct_data(Archive & ar, const my_class * t, const unsigned int file_version);
  17.     const int m_attribute;  // some immutable aspect of the instance
  18.     int m_state;            // mutable state of this instance
  19.     template<class Archive>
  20.     void serialize(Archive &ar, const unsigned int file_version){
  21.         ar & m_state;
  22.     }
  23. public:
  24.     // no default construct guarentees that no invalid object
  25.     // ever exists
  26.     my_class(int attribute) :
  27.         m_attribute(attribute),
  28.         m_state(0)
  29.     {}
  30. };
  31. namespace boost { namespace serialization {
  32. template<class Archive>
  33. inline void save_construct_data(
  34.     Archive & ar, const my_class * t, const unsigned int file_version
  35. ){
  36.     // save data required to construct instance
  37.     ar << t->m_attribute;
  38. }
  39.  
  40. template<class Archive>
  41. inline void load_construct_data(
  42.     Archive & ar, my_class * t, const unsigned int file_version
  43. ){
  44.     // retrieve data from archive required to construct new instance
  45.     int attribute;
  46.     ar >> attribute;
  47.     // invoke inplace constructor to initialize instance of my_class
  48.     ::new(t)my_class(attribute);
  49. }
  50. }} // namespace ...
  51.  
  52. int main() {
  53.     // create and open a character archive for output
  54.     std::ofstream ofs("filename");
  55.  
  56.     // create class instance
  57.     const my_class *g = new my_class(3);
  58.  
  59.     // save data to archive
  60.     {
  61.         boost::archive::text_oarchive oa(ofs);
  62.         // write class instance to archive
  63.         oa << g;
  64.         // archive and stream closed when destructors are called
  65.     }
  66.  
  67.     // ... some time later restore the class instance to its orginal state
  68.     my_class *newg;
  69.     {
  70.         // create and open an archive for input
  71.         std::ifstream ifs("filename");
  72.         boost::archive::text_iarchive ia(ifs);
  73.         // read class state from archive
  74.         ia >> newg;
  75.         // archive and stream closed when destructors are called
  76.     }
  77.     return 0;
  78. }