user1365063
user1365063

Reputation: 41

boost serialization polymorphic issues

Boost serialization of polymorphic classes seems not working ( 1.40+ boost), e.g. with the following code, I believe I followed the rule: of exporting the class and I tried on both gcc4.4 (ubuntu) and windows VS2010(with boost 1.48): in following program, I expect both 10 and 100 are printed, but it only print 10, that means it only serialized the base class;

I mostly copied the example from boost's document, yet it still doesn't work; anybody has any idea? thanks a lot LS

#include <iostream>
#include <sstream>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
#define NVP(X) X

class base {
public:
friend class boost::serialization::access;
base (){ v1 = 10;}
int v1;
template<class Archive>
void serialize(Archive & ar, const unsigned int file_version)
{
    ar & NVP(v1);
}
};


class derived : public base {
public:
friend class boost::serialization::access;
int v2 ;
derived() { v2 = 100;}
template<class Archive>
void serialize(Archive & ar, const unsigned int file_version){
    boost::serialization::base_object<base>(* this);
    ar & NVP(v2);
}
};
BOOST_CLASS_EXPORT(base);
BOOST_CLASS_EXPORT_GUID(derived, "derived");


int main ( ) 
{
std::stringstream ss;
boost::archive::text_oarchive ar(ss);
base *b = new derived();
ar << NVP(b);
std::cout << ss.str();
}

Upvotes: 2

Views: 1713

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

You forgot

virtual ~base() {}

which is not only required for the polymorphic seriialization to work (without it your class is not polymorphic), but I believe omitting it is a misdemeanor in 48 states. IANAL, so YMMV.

Oh, and it should be ar & boost::serialization::base_object<...>.

Upvotes: 6

Related Questions