提升序列化多态问题

时间:2012-04-30 05:05:13

标签: c++ serialization boost polymorphism boost-serialization

Boost序列化的多态类似乎不起作用(1.40+ boost),例如使用以下代码,我相信我遵循了以下规则:导出类和 我尝试了gcc4.4(ubuntu)和windows VS2010(使用boost 1.48): 在下面的程序中,我希望打印10和100,但它只打印10,这意味着它只序列化了基类;

我主要从boost的文档中复制了这个例子,但它仍然不起作用;有谁有任何想法? 非常感谢 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();
}

1 个答案:

答案 0 :(得分:6)

你忘记了

virtual ~base() {}

这不仅是多态连续化工作所必需的(没有它你的类是多态),但我相信省略它是48个州的轻罪。 IANAL,所以YMMV。

哦,它应该是ar & boost::serialization::base_object<...>