| 1 | #include <cassert>
|
|---|
| 2 | #include <fstream>
|
|---|
| 3 | #include <boost/shared_ptr.hpp>
|
|---|
| 4 | #include <boost/weak_ptr.hpp>
|
|---|
| 5 | #include <boost/serialization/serialization.hpp>
|
|---|
| 6 | #include <boost/archive/xml_oarchive.hpp>
|
|---|
| 7 | #include <boost/archive/xml_iarchive.hpp>
|
|---|
| 8 | #include <boost/serialization/nvp.hpp>
|
|---|
| 9 | #include <boost/serialization/export.hpp>
|
|---|
| 10 | #include <boost/serialization/shared_ptr.hpp>
|
|---|
| 11 | #include <boost/serialization/weak_ptr.hpp>
|
|---|
| 12 |
|
|---|
| 13 | struct Base1 {
|
|---|
| 14 | virtual ~Base1() {}
|
|---|
| 15 | // serialize
|
|---|
| 16 | friend class boost::serialization::access;
|
|---|
| 17 | template<class Archive>
|
|---|
| 18 | void serialize(Archive & /*ar*/, const unsigned int /* file_version */) {}
|
|---|
| 19 | };
|
|---|
| 20 |
|
|---|
| 21 | BOOST_CLASS_EXPORT(Base1)
|
|---|
| 22 |
|
|---|
| 23 | struct Base2 {
|
|---|
| 24 | virtual ~Base2() {}
|
|---|
| 25 | // serialize
|
|---|
| 26 | friend class boost::serialization::access;
|
|---|
| 27 | template<class Archive>
|
|---|
| 28 | void serialize(Archive & /*ar*/, const unsigned int /* file_version */) {}
|
|---|
| 29 | };
|
|---|
| 30 |
|
|---|
| 31 | BOOST_CLASS_EXPORT(Base2)
|
|---|
| 32 |
|
|---|
| 33 | struct Sub:public Base1, public Base2 {
|
|---|
| 34 | virtual ~Sub() {}
|
|---|
| 35 | boost::weak_ptr<Sub> wp_;
|
|---|
| 36 |
|
|---|
| 37 | // serialize
|
|---|
| 38 | friend class boost::serialization::access;
|
|---|
| 39 | template<class Archive>
|
|---|
| 40 | void serialize(Archive &ar, const unsigned int /* file_version */)
|
|---|
| 41 | {
|
|---|
| 42 | ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base1);
|
|---|
| 43 | ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base2);
|
|---|
| 44 | ar & BOOST_SERIALIZATION_NVP(wp_); // *1
|
|---|
| 45 | }
|
|---|
| 46 | };
|
|---|
| 47 |
|
|---|
| 48 | BOOST_CLASS_EXPORT(Sub)
|
|---|
| 49 |
|
|---|
| 50 | int main()
|
|---|
| 51 | {
|
|---|
| 52 | {
|
|---|
| 53 | // serialize
|
|---|
| 54 | boost::shared_ptr<Sub> s(new Sub);
|
|---|
| 55 | boost::shared_ptr<Base2> pb2(s);
|
|---|
| 56 | s->wp_ = s; // set weak_ptr. If not set, deserialize success.
|
|---|
| 57 | std::ofstream ofs("output.xml");
|
|---|
| 58 | assert(ofs);
|
|---|
| 59 | boost::archive::xml_oarchive oa(ofs);
|
|---|
| 60 | oa << boost::serialization::make_nvp("Base2", pb2);
|
|---|
| 61 | }
|
|---|
| 62 | {
|
|---|
| 63 | // de-serialize
|
|---|
| 64 | std::ifstream ifs("output.xml");
|
|---|
| 65 | assert(ifs);
|
|---|
| 66 | boost::archive::xml_iarchive ia(ifs);
|
|---|
| 67 | boost::shared_ptr<Base2> pb2;
|
|---|
| 68 | ia >> boost::serialization::make_nvp("Base2", pb2);
|
|---|
| 69 | // check
|
|---|
| 70 | // pb2's vptr is broken.
|
|---|
| 71 | assert(dynamic_cast<Sub *>(pb2.get()));
|
|---|
| 72 | }
|
|---|
| 73 | }
|
|---|