Ticket #3977: ref_direct2.cpp

File ref_direct2.cpp, 2.4 KB (added by kondo@…, 13 years ago)

replace TAB to white space version of ref_direct.cpp

Line 
1#include <fstream>
2#include <boost/archive/xml_oarchive.hpp>
3#include <boost/archive/xml_iarchive.hpp>
4#include <boost/serialization/nvp.hpp>
5
6struct MyInt {
7 MyInt():i_(0) {}
8 MyInt(int i):i_(i) {}
9 int i_;
10 friend class boost::serialization::access;
11 template<class Archive>
12 void serialize(Archive &ar, unsigned int const /* file_version */)
13 {
14 ar & BOOST_SERIALIZATION_NVP(i_);
15 }
16};
17
18struct Foo {
19 MyInt& ref_;
20
21 Foo(MyInt& ref):ref_(ref) {}
22
23 friend class boost::serialization::access;
24
25 template<class Archive>
26 void serialize(Archive &ar, unsigned int const /* file_version */) {}
27
28 template<class Archive>
29 friend void save_construct_data(Archive& ar,
30 Foo const* p, unsigned int const /* file_version */);
31
32 template<class Archive>
33 void load_construct_data(Archive& ar,
34 Foo* p, unsigned int const /* file_version */);
35};
36
37template<class Archive>
38void save_construct_data(Archive& ar, Foo const* p, unsigned int const /* file_version */)
39{
40#if 0
41 // OK
42 MyInt* pRef = &p->ref_;
43 ar << boost::serialization::make_nvp("ref_", pRef);
44#else
45 // Error
46 ar << boost::serialization::make_nvp("ref_", &p->ref_);
47#endif
48}
49
50template<class Archive>
51void load_construct_data(Archive & ar, Foo* p, unsigned int const /* file_version */)
52{
53 MyInt* pRef;
54 ar >> boost::serialization::make_nvp("ref_", pRef);
55 ::new(p) Foo(*pRef);
56}
57
58struct Bar {
59 Bar():mi_(1) {}
60 MyInt mi_;
61 Foo* pFoo_;
62
63 friend class boost::serialization::access;
64 template<class Archive>
65 void serialize(Archive &ar, unsigned int const /* file_version */)
66 {
67 ar & BOOST_SERIALIZATION_NVP(mi_);
68 ar & BOOST_SERIALIZATION_NVP(pFoo_);
69 }
70};
71
72int main()
73{
74 {
75 std::ofstream ofs("ref.xml");
76 Bar b1;
77 b1.pFoo_ = new Foo (b1.mi_);
78 b1.pFoo_->ref_.i_ = 2;
79 assert(b1.mi_.i_ == 2);
80 boost::archive::xml_oarchive oa(ofs);
81 oa << BOOST_SERIALIZATION_NVP(b1);
82 delete b1.pFoo_;
83 }
84 {
85 std::ifstream ifs("ref.xml");
86 boost::archive::xml_iarchive ia(ifs);
87 Bar b2;
88 ia >> BOOST_SERIALIZATION_NVP(b2);
89 assert(b2.mi_.i_ == 2);
90 assert(b2.pFoo_->ref_.i_ == 2);
91 b2.mi_.i_ = 3;
92 assert(b2.pFoo_->ref_.i_ == 3);
93 }
94}