Ticket #4981: serialize.cpp

File serialize.cpp, 2.6 KB (added by jsternberg <jonathansternberg@…>, 12 years ago)

example showing the problem

Line 
1
2#include <iostream>
3#include <sstream>
4#include <boost/shared_ptr.hpp>
5#include <boost/archive/text_oarchive.hpp>
6#include <boost/serialization/serialization.hpp>
7#include <boost/serialization/shared_ptr.hpp>
8
9class base
10{
11public:
12 base(std::string type_)
13 : type(type_)
14 {
15 }
16
17 // Make this polymorphic
18 virtual ~base() {}
19
20 virtual const boost::shared_ptr<base> clone() const
21 {
22 const boost::shared_ptr<base> object(new base(type));
23 return object;
24 }
25
26 std::string type;
27};
28
29class derived : public base
30{
31public:
32 derived(std::string type_, std::string string_)
33 : base(type_)
34 , string(string_)
35 {
36 }
37
38 virtual const boost::shared_ptr<base> clone() const
39 {
40 const boost::shared_ptr<derived> object(new derived(type, string));
41 return object;
42 }
43
44 std::string string;
45};
46
47template<class Archive>
48void serialize(Archive & ar, base& t,
49 const unsigned int file_version)
50{
51 std::cout << "serialized base " << t.type << std::endl;
52 ar & t.type;
53}
54
55BOOST_SERIALIZATION_SHARED_PTR(base)
56
57template<class Archive>
58void serialize(Archive & ar, derived& t,
59 const unsigned int file_version)
60{
61 std::cout << "serialize derived " << t.string << std::endl;
62 ar & boost::serialization::base_object<base>(t);
63 ar & t.string;
64}
65
66BOOST_SERIALIZATION_SHARED_PTR(derived)
67
68#include <boost/serialization/export.hpp>
69
70BOOST_CLASS_EXPORT(base)
71// This statement causes a compiler error
72//BOOST_CLASS_TRACKING(base, boost::serialization::track_never)
73BOOST_CLASS_EXPORT(derived)
74BOOST_CLASS_TRACKING(derived, boost::serialization::track_never)
75
76void write(boost::archive::text_oarchive& archive, boost::shared_ptr<base> t)
77{
78 const boost::shared_ptr<base> clone = t->clone();
79 archive << clone;
80}
81
82int main()
83{
84 std::stringstream sstream;
85 {
86 boost::archive::text_oarchive archive(sstream, boost::archive::no_tracking);
87
88 boost::shared_ptr<derived> d1(new derived("first", "first"));
89 boost::shared_ptr<derived> d2(new derived("second", "second"));
90
91 // Writes the first object properly
92 std::cout << "write first object" << std::endl;
93 write(archive, d1);
94 // If track_never is active, this will serialize only the derived class
95 // It will NOT serialize the base class with it
96 // If BOOST_CLASS_TRACKING is not used, this gets serialized as the
97 // first object.
98 std::cout << "write second object" << std::endl;
99 write(archive, d2);
100 }
101 std::cout << "archive contents: " << sstream.str() << std::endl;
102
103 return 0;
104}