| 1 | #include <fstream>
|
|---|
| 2 | #include <cassert>
|
|---|
| 3 |
|
|---|
| 4 | #include <boost/archive/xml_oarchive.hpp>
|
|---|
| 5 | #include <boost/archive/xml_iarchive.hpp>
|
|---|
| 6 |
|
|---|
| 7 | class Father;
|
|---|
| 8 |
|
|---|
| 9 | class Child {
|
|---|
| 10 | public:
|
|---|
| 11 | Child(Father* f) : father(f) {}
|
|---|
| 12 | Child() {}
|
|---|
| 13 |
|
|---|
| 14 | Father* father = nullptr;
|
|---|
| 15 |
|
|---|
| 16 | template<class Archive>
|
|---|
| 17 | void serialize(Archive & ar, const unsigned int version);
|
|---|
| 18 | };
|
|---|
| 19 |
|
|---|
| 20 | class Father {
|
|---|
| 21 | public:
|
|---|
| 22 | Child child;
|
|---|
| 23 | Father() : child(this) {}
|
|---|
| 24 |
|
|---|
| 25 | template<class Archive>
|
|---|
| 26 | void serialize(Archive & ar, const unsigned int version);
|
|---|
| 27 | };
|
|---|
| 28 |
|
|---|
| 29 | template<class Archive>
|
|---|
| 30 | void Child::serialize(Archive & ar, const unsigned int version) {
|
|---|
| 31 | ar & BOOST_SERIALIZATION_NVP(father);
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | template<class Archive>
|
|---|
| 35 | void Father::serialize(Archive & ar, const unsigned int version) {
|
|---|
| 36 | ar & BOOST_SERIALIZATION_NVP(child);
|
|---|
| 37 | }
|
|---|
| 38 |
|
|---|
| 39 | int main() {
|
|---|
| 40 | {
|
|---|
| 41 | std::ofstream ofs("filename");
|
|---|
| 42 | Father* father = new Father();
|
|---|
| 43 | Child* child = &father->child;
|
|---|
| 44 | boost::archive::xml_oarchive oa(ofs);
|
|---|
| 45 | oa << BOOST_SERIALIZATION_NVP(child); // reversing the order of de/serialization prevents the crash
|
|---|
| 46 | oa << BOOST_SERIALIZATION_NVP(father);
|
|---|
| 47 | assert(child == &father->child);
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | {
|
|---|
| 51 | Father* father = nullptr;
|
|---|
| 52 | Child* child = nullptr;
|
|---|
| 53 | std::ifstream ifs("filename");
|
|---|
| 54 | boost::archive::xml_iarchive ia(ifs);
|
|---|
| 55 | ia >> BOOST_SERIALIZATION_NVP(child);
|
|---|
| 56 | ia >> BOOST_SERIALIZATION_NVP(father);
|
|---|
| 57 | assert(child == &father->child); // fails
|
|---|
| 58 | }
|
|---|
| 59 | return 0;
|
|---|
| 60 | }
|
|---|