1 | #include <iostream>
|
---|
2 | #include <string>
|
---|
3 | #include <sstream>
|
---|
4 | #include <boost/archive/binary_oarchive.hpp>
|
---|
5 | #include <boost/archive/binary_iarchive.hpp>
|
---|
6 | #include <boost/shared_ptr.hpp>
|
---|
7 | #include <boost/serialization/shared_ptr.hpp>
|
---|
8 | #include <boost/serialization/base_object.hpp>
|
---|
9 |
|
---|
10 |
|
---|
11 |
|
---|
12 | class A {
|
---|
13 | public:
|
---|
14 | int a;
|
---|
15 |
|
---|
16 | A() { a = -1; }
|
---|
17 | virtual ~A() { }
|
---|
18 | virtual void printInfo() const {
|
---|
19 | std::cout << "A{a = " << a << "}";
|
---|
20 | }
|
---|
21 |
|
---|
22 | template<class Archive>
|
---|
23 | void serialize(Archive & ar, const unsigned int version) {
|
---|
24 | ar & a;
|
---|
25 | }
|
---|
26 | };
|
---|
27 |
|
---|
28 |
|
---|
29 | class B : public A {
|
---|
30 | public:
|
---|
31 | float b;
|
---|
32 |
|
---|
33 | B() {
|
---|
34 | b = -2.0;
|
---|
35 | }
|
---|
36 |
|
---|
37 | void printInfo() const {
|
---|
38 | std::cout << "B{base = ";
|
---|
39 | A::printInfo();
|
---|
40 | std::cout << ", b = " << b << "}";
|
---|
41 | }
|
---|
42 |
|
---|
43 | template<class Archive>
|
---|
44 | void serialize(Archive & ar, const unsigned int version) {
|
---|
45 | ar & boost::serialization::base_object<A>(*this);
|
---|
46 | ar & b;
|
---|
47 | }
|
---|
48 | };
|
---|
49 |
|
---|
50 |
|
---|
51 | class C : public A { };
|
---|
52 |
|
---|
53 |
|
---|
54 | int main() {
|
---|
55 | using namespace std;
|
---|
56 | cout << "Start boost-serialization test\n\n";
|
---|
57 |
|
---|
58 | boost::shared_ptr<A> p1( new B );
|
---|
59 | boost::shared_ptr<A> p2;
|
---|
60 |
|
---|
61 | ostringstream os(ios_base::out|ios_base::binary);
|
---|
62 | {
|
---|
63 | boost::archive::binary_oarchive oar(os);
|
---|
64 |
|
---|
65 | // this order is OK
|
---|
66 | /*
|
---|
67 | oar.register_type((B*)0);
|
---|
68 | oar.register_type((C*)0);
|
---|
69 | */
|
---|
70 |
|
---|
71 | // this order causes segmentation fault
|
---|
72 | oar.register_type((C*)0);
|
---|
73 | oar.register_type((B*)0);
|
---|
74 |
|
---|
75 | oar & p1;
|
---|
76 | }
|
---|
77 | const string data(os.str());
|
---|
78 |
|
---|
79 | cout << "Serialization done, data size [bytes]: " << data.size() << endl;
|
---|
80 |
|
---|
81 | istringstream is(data, ios_base::in|ios_base::binary);
|
---|
82 | {
|
---|
83 | boost::archive::binary_iarchive iar(is);
|
---|
84 | iar.register_type((B*)0);
|
---|
85 | iar & p2;
|
---|
86 | }
|
---|
87 |
|
---|
88 | cout << "Deserialization done\n";
|
---|
89 |
|
---|
90 | return 0;
|
---|
91 | }
|
---|