Boost 序列化

原文链接: https://blog.csdn.net/qq2399431200/article/details/45621921

1. 编译器 gcc, boost 1.55

2.1第一个简单的例子 —— Hello World ,将字符串内容归档到文本文件中

    #include <iostream>#include <fstream>#include <string>#include <cstdio>#include <boost/archive/text_oarchive.hpp>#include <boost/archive/text_iarchive.hpp>// 清单1.将字符串保存到文本归档文件中void save(){std::ofstream file("archive.txt");boost::archive::text_oarchive oa(file);std::string s = "Hello world\n";oa << s;  // oa & s; 清单3.使用&运算符执行“转储-恢复”操作}// 清单2.将字符串的内容加载到文本文件中void load(){std::ifstream file("archive.txt");boost::archive::text_iarchive ia(file);std::string s;ia >> s;  // ia & s; 清单3.使用&运算符执行“转储-恢复”操作std::cout << s << std::endl;}int main(){save();load();getchar();}

 2.2从xml文档文件执行“转储-恢复”操作

    // 清单4#include <iostream>#include <fstream>#include <string>#include <cstdio>#include <boost/archive/xml_iarchive.hpp>#include <boost/archive/xml_oarchive.hpp>void save(){std::ofstream file("archive.xml");boost::archive::xml_oarchive oa(file);std::string s = "Hello world! 你好,世界!\n";//如果您想使用 XML 归档文件,而不是文本归档文件,需要将数据打包到一个名为 BOOST_SERIALIZATION_NVP 的宏中oa & BOOST_SERIALIZATION_NVP(s);  }void load(){std::ifstream file("archive.xml");boost::archive::xml_iarchive ia(file);std::string s;ia & BOOST_SERIALIZATION_NVP(s);std::cout << s << std::endl;}int main(){save();load();getchar();}

 xml归档文件中的内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="10">
<s>Hello world! 你好,世界!
</s>
</boost_serialization>

 2.3对整数数组执行“转储-恢复”操作

    // 清单6#include <fstream>#include <iostream>#include <algorithm>#include <iterator>#include <cstdio>#include <boost/archive/xml_oarchive.hpp>#include <boost/archive/xml_iarchive.hpp>void save(){std::ofstream file("archive.xml");boost::archive::xml_oarchive oa(file);int arrary1[ ] = { 34, 78, 22, 1, 910 };oa & BOOST_SERIALIZATION_NVP(arrary1);}/*  是否可以仅通过指定指针 int* restored 完成此操作并为您恢复数组?答案是否定的。必须每次都指定大小。如果认真回答此问题的话,答案是对基本类型的指针进行序列化非常复杂。*/void load(){std::ifstream file("archive.xml");boost::archive::xml_iarchive ia(file);int restored[5];  //必须指定数组的大小ia & BOOST_SERIALIZATION_NVP(restored);std::ostream_iterator<int> oi(std::cout, " ");std::copy(restored, restored+5, oi);}int main(){save();load();getchar();}

xml归档文件中的内容:

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?><!DOCTYPE boost_serialization><boost_serialization signature="serialization::archive" version="10"><arrary1><count>5</count><item>34</item><item>78</item><item>22</item><item>1</item><item>910</item></arrary1></boost_serialization>

 2.4串行化STL集合

    // 清单8#include <iostream>#include <fstream>#include <algorithm>#include <iterator>#include <cstdio>#include <boost/archive/xml_iarchive.hpp>#include <boost/archive/xml_oarchive.hpp>#include <boost/serialization/list.hpp>#include <boost/serialization/vector.hpp>void save( ){std::ofstream file("archive.xml");boost::archive::xml_oarchive oa(file);float array[ ] = {34.2, 78.1, 22.221, 1.0, -910.88};std::list<float> L1(array, array+5);std::vector<float> V1(array, array+5);oa & BOOST_SERIALIZATION_NVP(L1);oa & BOOST_SERIALIZATION_NVP(V1);}void load(){std::ifstream file("archive.xml");boost::archive::xml_iarchive ia(file);std::list<float> L2;ia >> BOOST_SERIALIZATION_NVP(L2);  //不需要指定范围/大小std::vector<float> V2;ia >> BOOST_SERIALIZATION_NVP(V2);  //不需要指定范围/大小std::ostream_iterator<float> oi(std::cout, " ");std::copy(L2.begin(), L2.end(), oi );std::copy(V2.begin(), V2.end(), oi );}int main(){save();load();getchar();}

xml归档文件中内容:

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?><!DOCTYPE boost_serialization><boost_serialization signature="serialization::archive" version="10"><L1><count>5</count><item_version>0</item_version><item>34.200001</item><item>78.099998</item><item>22.221001</item><item>1</item><item>-910.88</item></L1><V1><count>5</count><item_version>0</item_version><item>34.200001</item><item>78.099998</item><item>22.221001</item><item>1</item><item>-910.88</item></V1></boost_serialization>

 2.5序列化自己的类型——serialize方法的侵入版本

 1     // 清单10 所谓“侵入”即serialize方法写到类中
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29         template<typename Archive>
30         void serialize(Archive& archive, const unsigned int version)
31         {
32             archive & BOOST_SERIALIZATION_NVP(m_day);
33             archive & BOOST_SERIALIZATION_NVP(m_month);
34             archive & BOOST_SERIALIZATION_NVP(m_year);
35         }
36     }date;
37      
38     void save( )
39     {
40         std::ofstream file("archive.xml");
41         boost::archive::xml_oarchive oa(file);
42         date d(15, 8, 1947);
43         oa & BOOST_SERIALIZATION_NVP(d);
44     }
45      
46     void load( )
47     {
48         std::ifstream file("archive.xml");
49         boost::archive::xml_iarchive ia(file);
50         date dr;
51         ia >> BOOST_SERIALIZATION_NVP(dr);
52         std::cout << dr;
53     }
54      
55     int main(void)
56     {
57         save();
58         load();
59         getchar();
60     }

xml归档文件的内容:

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?><!DOCTYPE boost_serialization><boost_serialization signature="serialization::archive" version="10"><d class_id="0" tracking_level="0" version="0"><m_day>15</m_day><m_month>8</m_month><m_year>1947</m_year></d></boost_serialization>

 2.6序列化自己的类型——serialize方法的非侵入版本

 1     // 清单11 所谓“非侵入”即serialize方法不必写在类中、不属于类
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29     }date;
30      
31     // 序列化相关的类和函数都属于boost::serialization命名空间里,所以自定义的serialize函数也可被其中的其它类和函数调用
32     namespace boost
33     {
34         namespace serialization
35         {
36             template<typename Archive>
37             void serialize(Archive& archive, date& d, const unsigned int version)
38             {
39                 archive & BOOST_SERIALIZATION_NVP(d.m_day);
40                 archive & BOOST_SERIALIZATION_NVP(d.m_month);
41                 archive & BOOST_SERIALIZATION_NVP(d.m_year);
42             }
43         }
44     }
45      
46      
47     void save( )
48     {
49         std::ofstream file("archive.xml");
50         boost::archive::xml_oarchive oa(file);
51         date d(15, 8, 1947);
52         oa & BOOST_SERIALIZATION_NVP(d);
53     }
54      
55     void load( )
56     {
57         std::ifstream file("archive.xml");
58         boost::archive::xml_iarchive ia(file);
59         date dr;
60         ia >> BOOST_SERIALIZATION_NVP(dr);
61         std::cout << dr;
62     }
63      
64     int main(void)
65     {
66         save();
67         load();
68         getchar();
69     }

 2.7通过基类指针转储派生类——使用xml文件归档

 1     // 清单13
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8     #include <string>
 9      
10     namespace
11     {
12         using std::cout;
13         using std::cin;
14         using std::endl;
15         using std::string;
16     }
17      
18     class CBase
19     {
20         friend class boost::serialization::access;
21         template<typename Archive>
22         void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(baseName); }
23         string baseName;
24     public:
25         CBase( ) { baseName = "class CBase"; }
26         virtual ~CBase( ) { }  //必须加一个virtual函数,否则“dynamic_cast<date*> (dr)”报error C2683: “dynamic_cast”:“CBase”不是多态类型 错误
27                               //这是C++多态属性决定的
28     };
29      
30      
31     class date : public CBase
32     {
33         unsigned int m_day;
34         unsigned int m_month;
35         unsigned int m_year;
36     public:
37         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
38         date( ):m_day(1),m_month(1),m_year(2000) { }
39         friend std::ostream& operator << (std::ostream& out, date& d)
40         {
41             out << "day:" << d.m_day << "\nmonth:" << d.m_month << "\nyear:" << d.m_year;
42             return out;
43         }
44         virtual ~date() { }
45     private:
46         friend class boost::serialization::access;
47         template<typename Archive>
48         void serialize(Archive& archive, const unsigned int version)
49         {
50             //archive & boost::serialization::base_object<CBase> (*this);  //用文本文档归档用此方法,当用于xml归档时会发生error C2664: “boost::mpl::assertion_failed”: 不能将参数 1 从“boost::mpl::failed ************boost::serialization::is_wrapper<T>::* ***********”转换为“boost::mpl::assert<false>::type”
51             
52             archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(CBase);   //用xml归档时,需要将父类对象包装,即用此宏,否则发生如上错误提示
54             archive & BOOST_SERIALIZATION_NVP(m_day);
55             archive & BOOST_SERIALIZATION_NVP(m_month);
56             archive & BOOST_SERIALIZATION_NVP(m_year);
57         }
58     };
59      
60     void save( )
61     {
62         std::ofstream file("archive.xml");
63         boost::archive::xml_oarchive oa(file);
64         oa.register_type<date>();
65         CBase *b = new date(16, 8, 1947);
66         oa & BOOST_SERIALIZATION_NVP(b);
67         delete b;
68     }
69      
70     void load( )
71     {
72         std::ifstream file("archive.xml");
73         boost::archive::xml_iarchive ia(file);
74         ia.register_type<date>();
75         CBase *dr;
76         ia >> BOOST_SERIALIZATION_NVP(dr);
77         date *dr2 = dynamic_cast<date*> (dr);
78         std::cout << *dr2;
79         delete dr2;
80     }
81      
82     int main(void)
83     {
84         save();
85         getchar();
86         load();
87         getchar();
88     }

 xml归档文件的内容:

    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?><!DOCTYPE boost_serialization><boost_serialization signature="serialization::archive" version="10"><b class_id="0" tracking_level="1" version="0" object_id="_0"><CBase class_id="1" tracking_level="1" version="0" object_id="_1"><baseName>class CBase</baseName></CBase><m_day>16</m_day><m_month>8</m_month><m_year>1947</m_year></b></boost_serialization>

 2.8通过基类指针转储派生类——使用文本文件归档

 1     // 注意和“3.7”的区别
 2      
 3     #include <boost/archive/text_oarchive.hpp>
 4     #include <boost/archive/text_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8     #include <string>
 9      
10     namespace
11     {
12         using std::cout;
13         using std::cin;
14         using std::endl;
15         using std::string;
16     }
17      
18     class CBase
19     {
20         friend class boost::serialization::access;
21         template<typename Archive>
22         void serialize(Archive& ar, const unsigned int version) { ar & baseName; }
23         string baseName;
24     public:
25         CBase( ) { baseName = "class CBase"; }
26         virtual ~CBase( ) { }  //必须加一个virtual函数,否则“dynamic_cast<date*> (dr)”报error C2683: “dynamic_cast”:“CBase”不是多态类型 错误
27         //这是C++多态属性决定的
28     };
29      
30      
31     class date : public CBase
32     {
33         unsigned int m_day;
34         unsigned int m_month;
35         unsigned int m_year;
36     public:
37         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
38         date( ):m_day(1),m_month(1),m_year(2000) { }
39         friend std::ostream& operator << (std::ostream& out, date& d)
40         {
41             out << "day:" << d.m_day << "\nmonth:" << d.m_month << "\nyear:" << d.m_year;
42             return out;
43         }
44         virtual ~date() { }
45     private:
46         friend class boost::serialization::access;
47         template<typename Archive>
48         void serialize(Archive& archive, const unsigned int version)
49         {
50             archive & boost::serialization::base_object<CBase> (*this);  //用文本文档归档用此方法,当用于xml归档时会发生error C2664: “boost::mpl::assertion_failed”: 不能将参数 1 从“boost::mpl::failed ************boost::serialization::is_wrapper<T>::* ***********”转换为“boost::mpl::assert<false>::type”
51             //archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(CBase);   //用xml归档时,需要将父类对象包装,即用此宏,否则发生如上错误提示
52             archive & m_day;
53             archive & m_month;
54             archive & m_year;
55         }
56     };
57      
58     void save( )
59     {
60         std::ofstream file("archive.txt");
61         boost::archive::text_oarchive oa(file);
62         oa.register_type<date>();
63         CBase *b = new date(16, 8, 1947);
64         oa & b;
65         delete b;
66     }
67      
68     void load( )
69     {
70         std::ifstream file("archive.txt");
71         boost::archive::text_iarchive ia(file);
72         ia.register_type<date>();
73         CBase *dr;
74         ia >> dr;
75         date *dr2 = dynamic_cast<date*> (dr);
76         std::cout << *dr2;
77         delete dr2;
78     }
79      
80     int main(void)
81     {
82         save();
83         getchar();
84         load();
85         getchar();
86     }

 文本文件归档内容:

22 serialization::archive 10 0 1 0
0 1 0
1 11 class CBase 16 8 1947

 2.9使用指针执行“转储-恢复”操作

 1     // 清单15
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29         template<typename Archive>
30         void serialize(Archive& archive, const unsigned int version)
31         {
32             archive & BOOST_SERIALIZATION_NVP(m_day);
33             archive & BOOST_SERIALIZATION_NVP(m_month);
34             archive & BOOST_SERIALIZATION_NVP(m_year);
35         }
36     }date;
37      
38     void save( )
39     {
40         std::ofstream file("archive.xml");
41         boost::archive::xml_oarchive oa(file);
42         date *d = new date(15, 8, 1947);
43         cout << d << endl;
44         oa & BOOST_SERIALIZATION_NVP(d);
45     }
46      
47     void load( )
48     {
49         std::ifstream file("archive.xml");
50         boost::archive::xml_iarchive ia(file);
51         date *dr;
52         ia >> BOOST_SERIALIZATION_NVP(dr);
53         std::cout << dr << endl;
54         cout << *dr;
55     }
56      
57     int main(void)
58     {
59         save();
60         load();
61         getchar();
62     } 

 运行结果:

0047A108
0047A6B8
day:15month:8year:1947

xml归档文件中的内容:

1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
2     <!DOCTYPE boost_serialization>
3     <boost_serialization signature="serialization::archive" version="10">
4     <d class_id="0" tracking_level="1" version="0" object_id="_0">
5         <m_day>15</m_day>
6         <m_month>8</m_month>
7         <m_year>1947</m_year>
8     </d>
9     </boost_serialization>

 2.10使用指针执行“转储-恢复”操作——将两个指针转储到同一个对象

 1     // 清单17
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29         template<typename Archive>
30         void serialize(Archive& archive, const unsigned int version)
31         {
32             archive & BOOST_SERIALIZATION_NVP(m_day);
33             archive & BOOST_SERIALIZATION_NVP(m_month);
34             archive & BOOST_SERIALIZATION_NVP(m_year);
35         }
36     }date;
37      
38     void save()
39     {
40         std::ofstream file("archive.xml");
41         boost::archive::xml_oarchive oa(file);
42         date *d = new date(15,8,1947);
43         cout << d << endl;
44         oa & BOOST_SERIALIZATION_NVP(d);
45         date *d2 = d;
46         oa & BOOST_SERIALIZATION_NVP(d2);
47     }
48      
49     void load()
50     {
51         std::ifstream file("archive.xml");
52         boost::archive::xml_iarchive ia(file);
53         date *dr;
54         ia >> BOOST_SERIALIZATION_NVP(dr);
55         cout << dr << endl;
56         cout << *dr << endl;
57         date *dr2;
58         ia >> BOOST_SERIALIZATION_NVP(dr2);
59         cout << dr2 << endl;
60         cout << *dr2;
61     }
62      
63     int main(void)
64     {
65         save();
66         load();
67         getchar();
68     } 

运行结果:

1 0010A108
2 0010A6B8
3 day:15month:8year:1947
4 0010A6B8
5 day:15month:8year:1947

 xml归档文件中的内容:

 1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 2     <!DOCTYPE boost_serialization>
 3     <boost_serialization signature="serialization::archive" version="10">
 4     <d class_id="0" tracking_level="1" version="0" object_id="_0">
 5         <m_day>15</m_day>
 6         <m_month>8</m_month>
 7         <m_year>1947</m_year>
 8     </d>
 9     <d2 class_id_reference="0" object_id_reference="_0"></d2>
10     </boost_serialization>

 2.11包含作为d的引用d2的归档文件

 1     // 清单19  和参考网页(IBM)中的那部分不一致
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29         template<typename Archive>
30         void serialize(Archive& archive, const unsigned int version)
31         {
32             archive & BOOST_SERIALIZATION_NVP(m_day);
33             archive & BOOST_SERIALIZATION_NVP(m_month);
34             archive & BOOST_SERIALIZATION_NVP(m_year);
35         }
36     }date;
37      
38     void save()
39     {
40         std::ofstream file("archive.xml");
41         boost::archive::xml_oarchive oa(file);
42         date *d = new date(15,8,1947);
43         cout << d << endl;
44         oa & BOOST_SERIALIZATION_NVP(d);
45         date* &d2 = d;     //d2 reference d
46         oa & BOOST_SERIALIZATION_NVP(d2);  
47     }
48      
49     void load()
50     {
51         std::ifstream file("archive.xml");
52         boost::archive::xml_iarchive ia(file);
53         date *dr;
54         ia >> BOOST_SERIALIZATION_NVP(dr);
55         cout << dr << endl;
56         cout << *dr << endl;
57         date *dr2;
58         ia >> BOOST_SERIALIZATION_NVP(dr2);
59         cout << dr2 << endl;
60         cout << *dr2;
61     }
62      
63     int main(void)
64     {
65         save();
66         load();
67         getchar();
68     }

 xml归档文件的内容:

 1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 2     <!DOCTYPE boost_serialization>
 3     <boost_serialization signature="serialization::archive" version="10">
 4     <d class_id="0" tracking_level="1" version="0" object_id="_0">
 5         <m_day>15</m_day>
 6         <m_month>8</m_month>
 7         <m_year>1947</m_year>
 8     </d>
 9     <d2 class_id_reference="0" object_id_reference="_0"></d2>
10     </boost_serialization>

 2.12将serialize拆分成save和load

        有时候,您不想使用同样的 serialize 方法来转储和恢复对象。在这种情况下,您可以将 serialize 方法拆分成两个方法,即save 和load,它们具有类似的签名。这两个方法都是之前定义的serialize 方法的一部分。此外,需要添加BOOST_SERIALIZATION_SPLIT_MEMBER 宏作为类定义的一部分。(引用参考文献[1])

 1     // 清单21
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
27             return out;
28         }
29     //     template<typename Archive>
30     //     void serialize(Archive& archive, const unsigned int version)
31     //     {
32     //         archive & BOOST_SERIALIZATION_NVP(m_day);
33     //         archive & BOOST_SERIALIZATION_NVP(m_month);
34     //         archive & BOOST_SERIALIZATION_NVP(m_year);
35     //     }
36             //将serialize函数分割成save和load函数,两个者实现的效果是等价的
37         template<class Archive>
38         void save(Archive& archive, const unsigned int version) const //注意 save 方法签名后的 const。如果没有 const 限定符,该代码将无法编译
39         {
40             archive << BOOST_SERIALIZATION_NVP(m_day);
41             archive << BOOST_SERIALIZATION_NVP(m_month);
42             archive << BOOST_SERIALIZATION_NVP(m_year);
43         }
44      
45         template<class Archive>
46         void load(Archive& archive, const unsigned int version)
47         {
48             archive >> BOOST_SERIALIZATION_NVP(m_day);
49             archive >> BOOST_SERIALIZATION_NVP(m_month);
50             archive >> BOOST_SERIALIZATION_NVP(m_year);
51         }
52         BOOST_SERIALIZATION_SPLIT_MEMBER( ) // must be part of class
53     }date;
54      
55     void save( )
56     {
57         std::ofstream file("archive.xml");
58         boost::archive::xml_oarchive oa(file);
59         date d(15, 8, 1991);
60         oa & BOOST_SERIALIZATION_NVP(d);
61     }
62      
63     void load( )
64     {
65         std::ifstream file("archive.xml");
66         boost::archive::xml_iarchive ia(file);
67         date dr;
68         ia >> BOOST_SERIALIZATION_NVP(dr);
69         std::cout << dr;
70     }
71      
72     int main(void)
73     {
74         save();
75         load();
76         getchar();
77     }

 2.13了解Boost::serialize的版本控制

    serialize、save 和 load 的方法签名都使用无符号整数版本作为最后一个参数。这些数字有什么用?随着时间变化,类的内部变量名称可能发生变化,添加新的字段或移除已有字段,等等。这是软件开发过程中的自然进程,除了归档文件仍然保存着关于数据类型原有状态的信息。为了规避这个问题,需要使用版本号。(引用参考文献[1])

        在date类的基础上增加一个unsigned int  ver变量用于保存当前类Mydate的版本号。

 1     // 清单22
 2      
 3     #include <boost/archive/xml_oarchive.hpp>
 4     #include <boost/archive/xml_iarchive.hpp>
 5     #include <iostream>
 6     #include <fstream>
 7     #include <cstdio>
 8      
 9     namespace
10     {
11         using std::cout;
12         using std::cin;
13         using std::endl;
14     }
15      
16     typedef struct date
17     {
18         unsigned int m_day;
19         unsigned int m_month;
20         unsigned int m_year;
21      
22         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
23         date( ):m_day(1),m_month(1),m_year(2000) { }
24         friend std::ostream& operator << (std::ostream& out, date& d)
25         {
26             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year << endl;
27             return out;
28         }
29         template<typename Archive>
30         void serialize(Archive& archive, const unsigned int version)
31         {
32             archive & BOOST_SERIALIZATION_NVP(m_day);
33             archive & BOOST_SERIALIZATION_NVP(m_month);
34             archive & BOOST_SERIALIZATION_NVP(m_year);
35         }
36     }date;
37     BOOST_CLASS_VERSION(date,0);
38      
39     // Mydate
40     typedef struct Mydate
41     {
42         unsigned int m_day;
43         unsigned int m_month;
44         unsigned int m_year;
45         unsigned int ver;  //版本
46      
47         Mydate(int d, int m, int y, int version):m_day(d), m_month(m) ,m_year(y), ver(version) {  }
48         Mydate( ):m_day(1),m_month(1),m_year(2000),ver(1) { }
49         friend std::ostream& operator << (std::ostream& out, Mydate& d)
50         {
51             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year << " -- Version:" << d.ver << endl;
52             return out;
53         }
54         template<typename Archive>
55         void serialize(Archive& archive, const unsigned int version)
56         {
57             archive & BOOST_SERIALIZATION_NVP(m_day);
58             archive & BOOST_SERIALIZATION_NVP(m_month);
59             archive & BOOST_SERIALIZATION_NVP(m_year);
60             if(version == 1)
61             {
62                 archive & BOOST_SERIALIZATION_NVP(ver);
63             }
64         }
65     }Mydate;
66     BOOST_CLASS_VERSION(Mydate,1);
67      
68     void save( )
69     {
70         std::ofstream file("version.xml");
71         boost::archive::xml_oarchive oa(file);
72         date d(15, 8, 1947);
73         oa & BOOST_SERIALIZATION_NVP(d);
74         Mydate myd(1, 1, 1991, 1);
75         oa & BOOST_SERIALIZATION_NVP(myd);
76     }
77      
78     void load( )
79     {
80         std::ifstream file("version.xml");
81         boost::archive::xml_iarchive ia(file);
82         date dr;
83         ia >> BOOST_SERIALIZATION_NVP(dr);
84         Mydate myd;
85         ia >> BOOST_SERIALIZATION_NVP(myd);
86         std::cout << dr;
87         std::cout << myd;
88     }
89      
90     int main(void)
91     {
92         save();
93         load();
94         getchar();
95     }

 运行结果:

day:15month:8year:1947
day:1month:1year:1991 -- Version:1

 xml归档文件中内容

 1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 2     <!DOCTYPE boost_serialization>
 3     <boost_serialization signature="serialization::archive" version="10">
 4     <d class_id="0" tracking_level="0" version="0">
 5         <m_day>15</m_day>
 6         <m_month>8</m_month>
 7         <m_year>1947</m_year>
 8     </d>
 9     <myd class_id="1" tracking_level="0" version="1">
10         <m_day>1</m_day>
11         <m_month>1</m_month>
12         <m_year>1991</m_year>
13         <ver>1</ver>
14     </myd>
15     </boost_serialization>
16      

 2.14 使用共享指针boost::shared_ptr执行“转储-恢复”操作

 1     // 清单23
 2      
 3     #include <iostream>
 4     #include <fstream>
 5     #include <string>
 6     #include <cstdio>
 7     #include <boost/archive/xml_iarchive.hpp>
 8     #include <boost/archive/xml_oarchive.hpp>
 9     #include <boost/serialization/shared_ptr.hpp>  //缺此头文件 —— error C2039: “serialize”: 不是“boost::shared_ptr<T>”的成员    d:\c++\boost\boost_1_55_0\boost\serialization\access.hpp
10      
11      
12     typedef struct date
13     {
14         unsigned int m_day;
15         unsigned int m_month;
16         unsigned int m_year;
17      
18         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
19         date( ):m_day(1),m_month(1),m_year(2000) { }
20         friend std::ostream& operator << (std::ostream& out, date& d)
21         {
22             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
23             return out;
24         }
25         template<typename Archive>
26         void serialize(Archive& archive, const unsigned int version)
27         {
28             archive & BOOST_SERIALIZATION_NVP(m_day);
29             archive & BOOST_SERIALIZATION_NVP(m_month);
30             archive & BOOST_SERIALIZATION_NVP(m_year);
31         }
32     }date;
33      
34     void save()
35     {
36         std::ofstream file("shared_ptr.xml");
37         boost::archive::xml_oarchive oa(file);
38         boost::shared_ptr<date> d (new date(15, 8, 1947));
39         oa & BOOST_SERIALIZATION_NVP(d);
40         // other code bellow
41     }
42      
43     void load()
44     {
45         std::fstream file("shared_ptr.xml");
46         boost::archive::xml_iarchive ia(file);
47         boost::shared_ptr<date> dr;
48         ia & BOOST_SERIALIZATION_NVP(dr);
49         std::cout << *dr;
50     }
51      
52     int main( )
53     {
54         save();
55         load();
56         getchar();
57     }

 xml文档中的内容:

 1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 2     <!DOCTYPE boost_serialization>
 3     <boost_serialization signature="serialization::archive" version="10">
 4     <d class_id="0" tracking_level="0" version="1">
 5         <px class_id="1" tracking_level="1" version="0" object_id="_0">
 6             <m_day>15</m_day>
 7             <m_month>8</m_month>
 8             <m_year>1947</m_year>
 9         </px>
10     </d>
11     </boost_serialization>

 2.15 指向栈对象的指针需要在实际对象之后转储

 1     // 清单24
 2      
 3     #include <iostream>
 4     #include <fstream>
 5     #include <string>
 6     #include <cstdio>
 7     #include <boost/archive/xml_iarchive.hpp>
 8     #include <boost/archive/xml_oarchive.hpp>
 9     #include <boost/serialization/shared_ptr.hpp>  //缺此头文件 —— error C2039: “serialize”: 不是“boost::shared_ptr<T>”的成员    d:\c++\boost\boost_1_55_0\boost\serialization\access.hpp
10      
11      
12     typedef struct date
13     {
14         unsigned int m_day;
15         unsigned int m_month;
16         unsigned int m_year;
17      
18         date(int d, int m, int y):m_day(d), m_month(m) ,m_year(y) {  }
19         date( ):m_day(1),m_month(1),m_year(2000) { }
20         friend std::ostream& operator << (std::ostream& out, date& d)
21         {
22             out << "day:" << d.m_day << "month:" << d.m_month << "year:" << d.m_year;
23             return out;
24         }
25         template<typename Archive>
26         void serialize(Archive& archive, const unsigned int version)
27         {
28             archive & BOOST_SERIALIZATION_NVP(m_day);
29             archive & BOOST_SERIALIZATION_NVP(m_month);
30             archive & BOOST_SERIALIZATION_NVP(m_year);
31         }
32     }date;
33      
34     void save()
35     {
36         std::ofstream file("stackobject.xml");
37         boost::archive::xml_oarchive oa(file);
38         date d(1,1,1991);
39         date *d2 = &d;
40         oa & BOOST_SERIALIZATION_NVP(d);  
41         oa & BOOST_SERIALIZATION_NVP(d2);  //指向栈对象的指针需要在实际对象之后转储
42     }
43      
44     void load()
45     {
46         std::fstream file("stackobject.xml");
47         boost::archive::xml_iarchive ia(file);
48         date dr;
49         ia & BOOST_SERIALIZATION_NVP(dr);
50         std::cout << dr << std::endl;
51         date *dr2;
52         ia & BOOST_SERIALIZATION_NVP(dr2);
53         std::cout << *dr2 << std::endl;
54     }
55      
56     int main( )
57     {
58         save();
59         load();
60         getchar();
61     }

 xml文档中的内容:

 1     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 2     <!DOCTYPE boost_serialization>
 3     <boost_serialization signature="serialization::archive" version="10">
 4     <d class_id="0" tracking_level="1" version="0" object_id="_0">
 5     <m_day>1</m_day>
 6     <m_month>1</m_month>
 7     <m_year>1991</m_year>
 8     </d>
 9     <d2 class_id_reference="0" object_id_reference="_0"></d2>
10     </boost_serialization>

  如果有多个指针指向同一个对象,Serialization 会使用 class_id_reference 将指针与原对象关联起来(每个对象都有一个唯一的类 ID)。原对象的每个后续指针都会将 object_id_reference 改成 _1、_2,以此类推。

3.参考文献

[1]. 《Boost Serialization 库》 http://www.ibm.com/developerworks/cn/aix/library/au-boostserialization/

4.C++ Boost::serialization简介

以下内容引用Boost库的“libs/serialization/doc/index.html”页面:    

         Here, we use the term "serialization" to meanthe reversible deconstruction of an arbitrary set of C++ data structuresto a sequence of bytes. Such a system can be used to reconstitutean equivalent structure in another program context. Depending onthe context, this might used implement object persistence, remoteparameter passing or other facility. In this system we use the term"archive" to refer to a specific rendering of thisstream of bytes. This could be a file of binary data, text data, XML, or some other created by the user of this library.
Our goals for such a system are:

    Code portability - depend only on ANSI C++ facilities.
    Code economy - exploit features of C++ such as RTTI, templates, and multiple inheritance, etc. where appropriate to make code shorter and simpler to use.
    Independent versioning for each class definition. That is, when a class definition changed, older files can still be imported to the new version of the class.
    Deep pointer save and restore. That is, save and restore of pointers saves and restores the data pointed to.
    Proper restoration of pointers to shared data.
    Serialization of STL containers and other commonly used templates.
    Data Portability - Streams of bytes created on one platform should be readable on any other.
    Orthogonal specification of class serialization and archive format. That is, any file format should be able to store serialization of any arbitrary set of C++ data structures without having to alter the serialization of any class.
    Non-intrusive. Permit serialization to be applied to unaltered classes. That is, don't require that classes to be serialized be derived from a specific base class or implement specified member functions. This is necessary to easily permit serialization to be applied to classes from class libraries that we cannot or don't want to have to alter.
    The archive interface must be simple enough to easily permit creation of a new type of archive.
    The archive interface must be rich enough to permit the creation of anarchive that presents serialized data as XML in a useful manner.

Other implementations
Before getting started I searched around for current implementations. I found several.

    MFC This is the one that I am very familiar with. I have used it for several years and have found it very useful. However it fails requirements 1, 2, 3, 6, 7, and 9. In spite of all the requirements not fulfilled, this is the most useful implementation I've found. It turns out that class versioning - partially implemented in MFC - really is indispensable for my applications. Inevitably, version 1.x of a shipping program needs to store more information in files than was originally provided for. MFC is the only one of these implementations that supports this - though only for the most derived class. Still it's better than nothing and does the job. MFC doesn't implement serialization of STL collections. Though it does so for MFC collections.
    CommonC++ libraries [1] As far as I can tell, this closely follows the MFC implementation but does address a few of the issues. It is portable and creates portable archives but skips versioning. It does support proper and complete restoration of pointers and STL collections. It does address compression though not in the way that I would prefer. The package would also benefit from having better documentation. So it fails to address 2, 3, 7, 8, and 9.
    Eternity [2] This is a bare bones package. It seems well coded but it really needs documentation and examples. It's not obvious how to use it without time consuming study of the source code. Recent versions do support files in XML format. This Fails 3, 6, 7?, 8, and 9.
    Holub's implementation [3] This is the article that first got me thinking about my own requirements for a serialization implementation. Interesting and worth the read if you can overlook the arrogant tone of the prose. This implementation fails 2, 3, 4, 5, and 6.
    s11n [13] This library has similar goals to this one. Some aspects of the implemenation are also similar. As of this writing, it would seem that:
        Portability(1) is guarenteed only for recent versions of GCC.
        Versioning(3) of class definitions is not explicitly supported by the library.
        it doesn't seem to automatically account for shared pointers(5). I concluded this from the documentation as well as the statement that serialization of graph like structures is not supported.
    Its has lots of differences - and lots in common with this implementation.  

原文:https://blog.csdn.net/qq2399431200/article/details/45621921 

转载于:https://www.cnblogs.com/lvchaoshun/p/10162389.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/248791.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker CE 的安装

一、Docker CE的安装1.先决条件运行环境&#xff1a;Ubuntu 64位或者其他支持Docker的64位系统运行配置&#xff0c;linux内核版本必须大于 3.10&#xff0c;否则会因为缺少容器运行所需的功能而出错。 2.在ubuntu下安装Docker CEUbuntu版本 Cosmic 18.10  Bionic 18.04 (…

nodeJS中的异步编程

nodejs 不是单线程 在博客项目中关于异步问题&#xff1a; 1.当用户添加一条博客时 需要通过post方式向服务器发送数据 后台获取用户以post方式拿到传送过来的数据 然后存入数据库&#xff1a; 上面的代码&#xff1a;创建一个空字符串 当用户向服务器发送请求时出发data事件将…

day01笔记

linux基本命令的学习&#xff1a; 1.查看主机名hostname 2.修改主机名hostnamectl set-hostname s16ds 3.linux命令提示符 [roots16ds ~]# # 超级用户的身份提示符 $ 普通用户的身份提示符4.修改命令提示符 PS1变量控制 [roots16ds ~]# echo $PS1 [\u\h \W]\$PS1[\u\h \w \t]…

angular 路由

1. vscode编辑器快速新建主路由&#xff1a; ng-router注意修改为 根路由为&#xff1a;‘forRoot()’app-route.module.ts;{ path:,redirectTo:/login,pathMatch:full } 当路由为空的时候&#xff0c;会重定向到/login路由&#xff0c;必须加上pathMatch:full 1 import { Rou…

nodeJs 操作数据库

首先在node中下载mysql包 npm install mysql 连接数据库 var mysql require(mysql); var con mysql.createConnection({host : localhost,user : root,password : root,database : blog });开启链接 con.connect();执行增删改查 不同功能创建不同的sql语句即可…

shell字体颜色应用

输出特效格式控制&#xff1a; \033[0m 关闭所有属性 \033[1m 设置高亮度 \03[4m 下划线 \033[5m 闪烁 \033[7m 反显 \033[8m 消隐 \033[30m -- \033[37m 设置前景色 \033[40m -- \033[47m 设置背景色 光标位置等的格式控制&#xff1a; …

Spring Boot 统一结果封装

ResultVo, 返回结果对象 Data public class ResultVo<T> {private Integer code;private String message;private T data; }ResultVoUtil, 封装返回结果 public class ResultVoUtil {public static<T> ResultVo<T> sucess(T data) {ResultVo<T> result…

总结面试题——Javascript

文章目录1.闭包2.作用域链3.JavaScript的原型 原型链 有什么特点4.事件代理5.Javascript如何实现继承6.this对象7.事件模型8.new操作符9.ajax原理10.解决跨域问题11.模块化开发怎么做12.异步加载js的方式有哪些13.会造成内存泄漏的操作14.XML和JSON的区别15.webpack16.AMD和Com…

js实现替换指定字符后面的内容(包括指定字符)

href 223d啥啥啥d dds word sss 1233;var indexOf href.indexOf(word);len href.substring(indexOf,href.length);&#xff08;包括指定字符串&#xff09; var newHref href.replace(len,替换内容);转载于:https://www.cnblogs.com/-lin/p/10172503.html

OAuth2.0 知多少

OAuth2.0 知多少 原文:OAuth2.0 知多少1. 引言 周末逛简书&#xff0c;看了一篇写的极好的文章&#xff0c;点击大红心点赞&#xff0c;就直接给我跳转到登录界面了&#xff0c;原来点赞是需要登录的。 可是没有我并没有简书账号&#xff0c;一直使用的QQ的集成登录。下面有一排…

五分钟带你摸透 Vue组件及组件通讯

一.组件化开发 组件 (Component) 是 Vue.js 强大的功能之一。组件可以扩展 HTML 元素&#xff0c;封装可重用的代 码。在较高层面上&#xff0c;组件是自定义元素&#xff0c;Vue.js 的编译器为它添加特殊功能。在vue中都是组件化开发的&#xff0c;组件化开发就是把一个完整的…

Parameter 'userName' not found. Available parameters are [1, 0, param1, param2]

Mapper接口的方法的参数没有加&#xff1a;Param("xxx")注解&#xff0c;或者是xxx写不对转载于:https://www.cnblogs.com/linliquan/p/10987136.html

微信公众号开发-接入

一 首先实现内网穿透&#xff0c;公众号需要连接我们的服务器&#xff0c;内外无法访问&#xff0c;所以先实现自己的内网可以测试时连接外网&#xff0c;下载natapp&#xff0c;选择windows&#xff0c;顺便下载config,ini 配置文件。注册好购买免费的隧道 然后将token写入配置…

Vue 项目上线优化

上线项目的优化 优化上线项目&#xff0c;首先在上线打包时我们通过babel插件将console清除&#xff0c;当然对项目打包后的体积的影响是微乎其微&#xff0c;对项目的入口文件的改善也是很有必要的&#xff0c;因为在开发阶段和上线如果我们使用的是同一入口文件&#xff0c;…

Python并发编程—进程

多任务编程 1.意义&#xff1a; 充分利用计算机多核资源&#xff0c;提高程序的运行效率。 2.实现方案 &#xff1a;多进程 &#xff0c; 多线程 3.并行与并发 并发 &#xff1a; 同时处理多个任务&#xff0c;内核在任务间不断的切换达到好像多个任务被同时执行的效果&#xf…

Vue 脚手架中的.eslintrc.js代码规范 的解决

在我们使用Vue脚手架 创建项目时 尤其是团队共同开发项目时 会按照一个共同的代码规范来编程 创建Vue脚手架中有一个.eslintrc.js格式 但是在编程中我们通常会使用 shiftaltf 进行代码格式化 但是由于格式化后的代码 与Vue中的.eslintrc规范不协调 尤其是 “” &#xff1b; 以…

innodb_locks_unsafe_for_binlog分析

mysql数据库中默认的隔离级别为repeat-read. innodb默认使用了next-gap算法&#xff0c;这种算法结合了index-row锁和gap锁。正因为这样的锁算法&#xff0c;innodb在可重复读这样的默认隔离级别上&#xff0c;可以避免幻象的产生。 innodb_locks_unsafe_for_binlog最主要的作用…

emacs的使用方法

emacs的使用方法 emacs配置&#xff1a; 将文件命名为.emacs&#xff0c;把配置敲进去&#xff0c;放在home文件夹 emacs命令行&#xff1a; altx打开命令行 编译&#xff1a; 在命令行输入compile&#xff0c;回车&#xff0c;会出现make -k&#xff0c;删掉它&#xff0c;输入…

前端面试---Vue部分考点梳理

一. Vue的使用 1. Vue的基本使用 指令 插值 插值 表达式 指令 动态属性 v-html 会有XSS风险 会覆盖子组件 computed 和 watch computed 有缓存 data不变则不会重新计算watch 如何深度监听watch 监听引用类型时 拿不到oldVal v-for v-for 和 v-if 不能同时使用:key的值尽量…

.net core实现跨域

什么是跨域在前面已经讲解过了&#xff0c;这里便不再讲解&#xff0c;直接上代码。 一、后台API接口 用.net core创建一个Web API项目负责给前端界面提供数据。 二、前端界面 建立两个MVC项目&#xff0c;模拟不同的ip&#xff0c;在view里面添加按钮调用WEB API提供的接口进行…