Boost logo

Boost Users :

Subject: Re: [Boost-users] Boost.Serialization: Restoring object state (preventcreation of a new object)?
From: Robert Ramey (ramey_at_[hidden])
Date: 2010-08-30 12:11:18


ray_at_[hidden] wrote:

If an object is serialized (saved) from a pointer, the loading part automatically creates (instantiates) a new object. However, there are situations when the object is already created and all we need is to restore its state.

The following code demonstrates one possible - although not elegant - solution using a temporary object:

#include <fstream>#include <iostream>#include <boost/archive/xml_iarchive.hpp>#include <boost/archive/xml_oarchive.hpp>#include <boost/serialization/string.hpp>#include <boost/serialization/export.hpp>class A{public: A() : m_val(100) { } int m_val;private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(m_val); }};int main(int argc, char* argv[]){ A *a = new A(); // Save the object { std::ofstream os("d:/test.xml"); boost::archive::xml_oarchive oa(os); // Save from pointer oa & BOOST_SERIALIZATION_NVP(a); } // Change the object state a->m_val = 200; // Restore the state { std::ifstream is("d:/test.xml"); boost::archive::xml_iarchive ia(is); A* aTemp; ia & BOOST_SERIALIZATION_NVP(aTemp); a->m_val = aTemp->m_val; // Copy object state assert(a->m_val == 100); delete aTemp; }}Just avoid serialization through a pointer, serialize either theobject or a reference to the object.change the above to: A a; // Save the object { std::ofstream os("d:/test.xml"); boost::archive::xml_oarchive oa(os); // Save from pointer oa & BOOST_SERIALIZATION_NVP(a); } // Change the object state a->m_val = 200; // Restore the state { std::ifstream is("d:/test.xml"); boost::archive::xml_iarchive ia(is); ia & BOOST_SERIALIZATION_NVP(aTemp); ar >> a // Copy object state assert(a->m_val == 100); delete aTemp; }Robert Ramey



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net