16 Şubat 2018 Cuma

serialization ve Default Constructor

Default Constructor
Anladığım kadarıyla boost serialization yapısının çalışması için, yazılan ve okunan sınıfların default constructor metodlarına sahip olması gerekiyor. Açıklaması şöyle.
If I save object (I have only pointer to this object) and then try to load it, > the sequence is following:
  1. Calling the constructor of this object.
  2. Copying the data.
Bir başka açıklama şöyle.
The main issue is that all classes have non default constructors and const children. To overcome this issue, I followed the doc and overloaded load_construct_data and save_construct_data.

Eğer default constructor yoksa
Örnek
Şöyle yaparız.
////Overrides for non-default constructor used
namespace boost
{
  namespace serialization
  {
    template<class Archive>
    inline void load_construct_data(Archive & ar, Foo * f, 
                                    const unsigned int version)
    {
      // retrieve data from archive required to construct new instance
      int id;
      ar >> id;
      // invoke inplace constructor to initialize instance of Feature
      ::new(f)Foo (id);
    }

    template<class Archive>
    inline void save_construct_data(Archive & ar, const Foo * f,
                                    const unsigned int version)
    {
      // save data required to construct instance
      ar << f->id();
    }
  }
}
Örnek
Şöyle yaparız.
//forward declarations of custom boost functions to friend them in the class
namespace b_ser = boost::serialization;
namespace boost {
namespace serialization {

  template <class Archive>
  void load_construct_data(Archive &ar, Foo *g, const unsigned int);

  template <class Archive>
  void save_construct_data(Archive &ar, const Foo *f, const unsigned int);


} // namespace serialization
} // namespace boost
Söyle yaparız.
struct Foo  {

  template <class Archive>
  void serialize(Archive &ar, const unsigned int version) {
    ar &boost::serialization::base_object<Expr>(*this);
  }
  template <class Archive>
  friend void b_ser::save_construct_data(Archive &ar, const Foo *f,
                                         const unsigned int) {
    ar << f->n;
  }
  template <class Archive>
  friend void b_ser::load_construct_data(Archive &ar, Foo *f,
                                         const unsigned int) {
    int n;
    ar >> n;
    ::new (f) Foo(n);
  }
};
Kullanmak için şöyle yaparız.
Foo *f;
is >> f;

Hiç yorum yok:

Yorum Gönder