Separating save and load methods does not mean that you need to save two copies of the serialization code. You can separate them and then join them again using a common function.
private: friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER() template <class Archive> void save(Archive& ar, const unsigned int version) const { const_cast<Example*>(this)->common_serialize(ar, version); } template <class Archive> void load(Archive& ar, const unsigned int version) { common_serialize(ar, version); sqrt_num = -1; } template <class Archive> void common_serialize(Archive& ar, const unsigned int version) { ar & num; }
You probably noticed const_cast . This is an unfortunate warning against this idea. Although the serialize member function is not constant for save operations, the save member function must be const. Until the object you serialize was originally declared const, it is safe to discard it as shown above. The documentation briefly mentions the need for dropping for const members ; it looks like.
With the above changes, your code will correctly print "2" for ex1 and ex2 , and you will only need to save one copy of the serialization code. The load code contains only code specific for reinitializing the objectโs internal cache; the save function does not apply to the cache.
source share