Boost - 序列化 (Serialization)

程序開發中,序列化是經常需要用到的。像一些相對高級語言,比如JAVA, C#都已經很好的支持了序列化,那麼C++呢?當然一個比較好的選擇就是用Boost,這個號稱C++準標準庫的東西。

什麼時候需要序列化呢?舉個例子,我們定義了一個class,比如:

  1. class CCar  
  2. {  
  3. public:  
  4.     void SetName(std::string& strName){m_strName = strName;}  
  5.     std::string GetName() const{return m_strName;}  
  6. private:  
  7.     std::string m_strName;  
  8. };  


然後我們想把這個類的一個對象保存到文件中或者通過網絡發出去,怎麼辦呢?答案就是:把這個對象序列化,然後我們可以得到一個二進制字節流,或者XML格式表示等等。

這樣我們就可以保存這個對象到文件中或者通過網絡發出去了。把序列化的數據進行反序列化,就可以得到一個CCar對象了。

Boost已經很好的支持了序列化這個東西,很好很強大。

Boost網站上有介紹: http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html

對於序列化,Boost是這麼定義的:

Here, we use the term "serialization" to mean the reversible deconstruction of an arbitrary set of C++ data structures to a sequence of bytes.  Such a system can be used to reconstitute an equivalent structure in another program context.  Depending on the context, this might used implement object persistence, remote parameter passing or other facility. In this system we use the term"archive" to refer to a specific rendering of this stream of bytes.  This could be a file of binary data, text data,  XML, or some other created by the user of this library.

這段英文很簡單,我相信大多數程序員都能看的懂。

基本上Boost序列化可以分爲兩種模式:侵入式(intrusive)和非侵入式(non-intrusive)

 

侵入式(intrusive)

先來看看侵入式。我們先來定義一個類,這個類支持序列化:

  1. class CMyData  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         ar & _tag;  
  10.         ar & _text;  
  11.     }  
  12.   
  13.       
  14. public:  
  15.     CMyData():_tag(0), _text(""){}  
  16.   
  17.     CMyData(int tag, std::string text):_tag(tag), _text(text){}  
  18.   
  19.     int GetTag() const {return _tag;}  
  20.     std::string GetText() const {return _text;}  
  21.   
  22. private:  
  23.     int _tag;  
  24.     std::string _text;  
  25. };  


 

其中,我們可以看到這些代碼:

  1. friend class boost::serialization::access;  
  2.   
  3.     template<class Archive>  
  4.     void serialize(Archive& ar, const unsigned int version)  
  5.     {  
  6.         ar & _tag;  
  7.         ar & _text;  
  8.     }  

這些代碼就是用來實現序列化的,這些代碼存在於類CMyData中,也就是爲什麼稱這種模式是“侵入式”的原因了。

看看怎麼把這個對象序列化。這裏,我把這個對象以二進制的方式保存到了一個ostringstream中了,當然也可以保存爲其他形式,比如XML。也可以保存到文件中。代碼都是類似的。

  1. void TestArchive1()  
  2. {  
  3.     CMyData d1(2012, "China, good luck");  
  4.     std::ostringstream os;  
  5.     boost::archive::binary_oarchive oa(os);  
  6.     oa << d1;//序列化到一個ostringstream裏面  
  7.   
  8.     std::string content = os.str();//content保存了序列化後的數據。  
  9.   
  10.     CMyData d2;  
  11.     std::istringstream is(content);  
  12.     boost::archive::binary_iarchive ia(is);  
  13.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  14.   
  15.     std::cout << "CMyData tag: " << d2.GetTag() << ", text: " << d2.GetText() << "\n";  
  16. }  

先生成一個CMyData的對象,然後序列化保存到一個ostringstream中,接着再把這個序列化的數據反序列化,得到原來的對象,打印出來,我們會發現反序列化的對象的數據成員跟序列化前的對象一模一樣。哈哈,成功了,簡單吧。至於Boost怎麼實現這個過程的,看Boost源代碼吧,Boost的網站上也有一些介紹。Boost確實設計的很巧妙,不得不佩服那幫傢伙。

那麼可以序列化CMyData的子類嗎,答案是肯定的。其實很簡單就是在子類的序列化函數裏面先序列化基類的。看看代碼就明白了:

  1. class CMyData_Child: public CMyData  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         // serialize base class information  
  10.         ar & boost::serialization::base_object<CMyData>(*this);  
  11.         ar & _number;  
  12.     }  
  13.   
  14.   
  15. public:  
  16.     CMyData_Child():_number(0.0){}  
  17.   
  18.     CMyData_Child(int tag, std::string text, float number):CMyData(tag, text), _number(number){}  
  19.   
  20.     float GetNumber() const{return _number;}  
  21.   
  22. private:  
  23.     float _number;  
  24. };  
  25.   
  26. void TestArchive3()  
  27. {  
  28.     CMyData_Child d1(2012, "China, good luck", 1.2);  
  29.     std::ostringstream os;  
  30.     boost::archive::binary_oarchive oa(os);  
  31.     oa << d1;//序列化到一個ostringstream裏面  
  32.   
  33.     std::string content = os.str();//content保存了序列化後的數據。  
  34.   
  35.     CMyData_Child d2;  
  36.     std::istringstream is(content);  
  37.     boost::archive::binary_iarchive ia(is);  
  38.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  39.   
  40.     std::cout << "CMyData_Child tag: " << d2.GetTag() << ", text: " << d2.GetText() << ", number: "<<d2.GetNumber() << "\n";  
  41. }  


 

 

非侵入式(non-intrusive)

侵入式的缺點就是需要在class裏面加一些代碼,那麼有時候可能這個class已經存在了,或者我們並不想往裏面加入這麼些代碼,那麼怎麼辦呢?ok,輪到非侵入式出場了。

比方說我們有這麼個類:

  1. class CMyData2  
  2. {  
  3. public:  
  4.     CMyData2():_tag(0), _text(""){}  
  5.   
  6.     CMyData2(int tag, std::string text):_tag(tag), _text(text){}  
  7.   
  8.     int _tag;  
  9.     std::string _text;  
  10. };  

那麼我們可以這麼序列化:

  1. namespace boost {  
  2.     namespace serialization {  
  3.   
  4.         template<class Archive>  
  5.         void serialize(Archive & ar, CMyData2 & d, const unsigned int version)  
  6.         {  
  7.             ar & d._tag;  
  8.             ar & d._text;  
  9.         }  
  10.   
  11.     } // namespace serialization  
  12. // namespace boost  


 然後調用還是跟侵入式一模一樣,看:

  1. void TestArchive2()  
  2. {  
  3.     CMyData2 d1(2012, "China, good luck");  
  4.     std::ostringstream os;  
  5.     boost::archive::binary_oarchive oa(os);  
  6.     oa << d1;//序列化到一個ostringstream裏面  
  7.   
  8.     std::string content = os.str();//content保存了序列化後的數據。  
  9.   
  10.     CMyData2 d2;  
  11.     std::istringstream is(content);  
  12.     boost::archive::binary_iarchive ia(is);  
  13.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  14.   
  15.     std::cout << "CMyData2 tag: " << d2._tag << ", text: " << d2._text << "\n";  
  16. }  


成功。跟侵入式相比,非侵入式省去了在具體類裏面加入序列化代碼。但是我們看看非侵入式模式裏面的類的定義,我們會發現我們把數據成員搞成public的了。這是爲什麼呢?看看這個就明白了:

  1. template<class Archive>  
  2.         void serialize(Archive & ar, CMyData2 & d, const unsigned int version)  
  3.         {  
  4.             ar & d._tag;  
  5.             ar & d._text;  
  6.         }  

原來序列化函數需要訪問數據成員。這就是非侵入式的一個缺點了:需要把數據成員暴露出來。通過直接訪問數據成員也好,通過函數訪問也好,總之需要這個類把數據成員暴露出來,這樣序列化函數才能訪問。世界上沒有十全十美的東西,有時我們得到一個東西,往往會失去另外一個東西,不是嗎?

侵入式和非侵入式各有各的用處,看具體情況來決定用哪個了。

非侵入式可以支持子類序列化嗎?可以。跟侵入式一樣,其實也就是先序列化一下基類,然後再序列化子類的數據成員。看代碼:


  1. class CMyData2_Child: public CMyData2  
  2. {  
  3. public:  
  4.     CMyData2_Child():_number(0.0){}  
  5.   
  6.     CMyData2_Child(int tag, std::string text, float number):CMyData2(tag, text), _number(number){}  
  7.   
  8.     float _number;  
  9. };  
  10.   
  11. namespace boost {  
  12.     namespace serialization {  
  13.   
  14.         template<class Archive>  
  15.         void serialize(Archive & ar, CMyData2_Child & d, const unsigned int version)  
  16.         {  
  17.             // serialize base class information  
  18.             ar & boost::serialization::base_object<CMyData2>(d);  
  19.             ar & d._number;  
  20.         }  
  21.   
  22.     } // namespace serialization  
  23. // namespace boost  
  24.   
  25. void TestArchive4()  
  26. {  
  27.     CMyData2_Child d1(2012, "test non-intrusive child class", 5.6);  
  28.     std::ostringstream os;  
  29.     boost::archive::binary_oarchive oa(os);  
  30.     oa << d1;//序列化到一個ostringstream裏面  
  31.   
  32.     std::string content = os.str();//content保存了序列化後的數據。  
  33.   
  34.     CMyData2_Child d2;  
  35.     std::istringstream is(content);  
  36.     boost::archive::binary_iarchive ia(is);  
  37.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  38.   
  39.     std::cout << "CMyData2_Child tag: " << d2._tag << ", text: " << d2._text << ", number: "<<d2._number<<"\n";  
  40. }  

 

好了,以上就是序列化的簡單用法。接下里我們來重點關注一下數據成員的序列化,假如我們的類裏面有指針,那麼還能序列化嗎?比如下面的代碼,會發生什麼事?


序列化指針數據成員

  1. class CMyData  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         ar & _tag;  
  10.         ar & _text;  
  11.     }  
  12.   
  13.   
  14. public:  
  15.     CMyData():_tag(0), _text(""){}  
  16.   
  17.     CMyData(int tag, std::string text):_tag(tag), _text(text){}  
  18.   
  19.     int GetTag() const {return _tag;}  
  20.     std::string GetText() const {return _text;}  
  21.   
  22. private:  
  23.     int _tag;  
  24.     std::string _text;  
  25. };  
  26. class CMyData_Child: public CMyData  
  27. {  
  28. private:  
  29.     friend class boost::serialization::access;  
  30.   
  31.     template<class archive="">  
  32.     void serialize(Archive& ar, const unsigned int version)  
  33.     {  
  34.         // serialize base class information  
  35.         ar & boost::serialization::base_object<cmydata>(*this);  
  36.         ar & _number;  
  37.     }  
  38.   
  39.   
  40. public:  
  41.     CMyData_Child():_number(0.0){}  
  42.   
  43.     CMyData_Child(int tag, std::string text, float number):CMyData(tag, text), _number(number){}  
  44.   
  45.     float GetNumber() const{return _number;}  
  46.   
  47. private:  
  48.     float _number;  
  49. };  
  50. class CMyData_Container  
  51. {  
  52. private:  
  53.     friend class boost::serialization::access;  
  54.   
  55.     template<class Archive>  
  56.     void serialize(Archive& ar, const unsigned int version)  
  57.     {  
  58.         for(int i = 0; i < 3; i++)  
  59.         {  
  60.             ar & pointers[i];  
  61.         }  
  62.     }  
  63. public:  
  64.     CMyData* pointers[3];  
  65. };  
  66.   
  67. void TestPointerArchive()  
  68. {  
  69.     std::string content;  
  70.     {  
  71.         CMyData d1(1, "a");  
  72.         CMyData_Child d2(2, "b", 1.5);  
  73.   
  74.         CMyData_Container containter;  
  75.         containter.pointers[0] = &d1;  
  76.         containter.pointers[1] = &d2;  
  77.         containter.pointers[2] = &d1;  
  78.   
  79.         std::ostringstream os;  
  80.         boost::archive::binary_oarchive oa(os);  
  81.         oa << containter;  
  82.   
  83.         content = os.str();  
  84.     }  
  85.   
  86.     //反序列化  
  87.     {  
  88.         CMyData_Container container;  
  89.         std::istringstream is(content);  
  90.         boost::archive::binary_iarchive ia(is);  
  91.         ia >> container;  
  92.   
  93.         for (int i = 0; i < 3; i++)  
  94.         {  
  95.             CMyData* d = container.pointers[i];  
  96.             std::cout << "pointer" << i + 1 <<": " << d->GetText() << "\n";  
  97.   
  98.             if (i == 1)  
  99.             {  
  100.                 CMyData_Child* child = reinterpret_cast<CMyData_Child*>(d);  
  101.                 std::cout << "pointer" << i + 1 <<", number: " << child->GetNumber() << "\n";  
  102.             }  
  103.         }  
  104.     }  
  105. }</cmydata></class>  


 注意,我們在CMyData_Container對象裏面放進去了3個指針,其中第二個指針是CMyData的子類。

然後進行序列化,再反序列化,我們會發現,第一個,第三個指針輸出了正確的信息,然而第二個指針有點問題,本身我們存進去的時候是個CMyData_Child 對象,通過測試我們可以發現,CMyData_Child的基類部分,我們可以正確的輸出,但是CMyData_Child的成員_number,卻得不到正確信息。這是個問題。

也就是說,序列化指針是可以的,但是需要注意多態的問題。假如我們不需要考慮多態,那麼以上的代碼就可以正常工作了。但是如果要考慮多態的問題,那麼就得特殊處理了。下面再來介紹序列化多態指針。

 

 序列化多態指針數據成員

上一個章節裏面演示瞭如果序列化指針成員,但是有個問題,就是當基類指針指向一個派生類對象的時候,然後序列化這個指針,那麼派生類的信息就被丟掉了。這個很不好。那麼怎麼來解決這個問題呢?很幸運,Boost的開發人員已經考慮到了這個問題。再一次感受到Boost的強大。

有兩種方法可以解決這個問題:

1. registration

2. export

具體可以參考: http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/serialization.html#derivedpointers

這裏我們介紹第二種方式,這種方式比較簡單,也用的比較好。就是通過一個宏把派生類給命名一下。

這個關鍵的宏是:BOOST_CLASS_EXPORT_GUID

相關解釋:

The macro BOOST_CLASS_EXPORT_GUID associates a string literal with a class. In the above example we've used a string rendering of the class name. If a object of such an "exported" class is serialized through a pointer and is otherwise unregistered, the "export" string is  included in the archive. When the archive  is later read, the string literal is used to find the class which  should be created by the serialization library. This permits each class to be in a separate header file along with its  string identifier. There is no need to maintain a separate "pre-registration"  of derived classes that might be serialized.  This method of registration is referred to as "key export".

如何使用這個神奇的宏BOOST_CLASS_EXPORT_GUID來實現序列化指向派生類的指針呢?先給出代碼:

  1. class CMyData  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         ar & _tag;  
  10.         ar & _text;  
  11.     }  
  12.   
  13.       
  14. public:  
  15.     CMyData():_tag(0), _text(""){}  
  16.   
  17.     CMyData(int tag, std::string text):_tag(tag), _text(text){}  
  18.     virtual ~CMyData(){}  
  19.   
  20.     int GetTag() const {return _tag;}  
  21.     std::string GetText() const {return _text;}  
  22.   
  23. private:  
  24.     int _tag;  
  25.     std::string _text;  
  26. };  
  27.   
  28. class CMyData_Child: public CMyData  
  29. {  
  30. private:  
  31.     friend class boost::serialization::access;  
  32.   
  33.     template<class Archive>  
  34.     void serialize(Archive& ar, const unsigned int version)  
  35.     {  
  36.         // serialize base class information  
  37.         ar & boost::serialization::base_object<CMyData>(*this);  
  38.         ar & _number;  
  39.     }  
  40.   
  41.   
  42. public:  
  43.     CMyData_Child():_number(0.0){}  
  44.   
  45.     CMyData_Child(int tag, std::string text, float number):CMyData(tag, text), _number(number){}  
  46.   
  47.     float GetNumber() const{return _number;}  
  48.   
  49. private:  
  50.     float _number;  
  51. };  
  52.   
  53. BOOST_CLASS_EXPORT_GUID(CMyData_Child, "CMyData_Child")  
  54.   
  55. class CMyData_Container  
  56. {  
  57. private:  
  58.     friend class boost::serialization::access;  
  59.   
  60.     template<class Archive>  
  61.     void serialize(Archive& ar, const unsigned int version)  
  62.     {  
  63.         for(int i = 0; i < 3; i++)  
  64.         {  
  65.             ar & pointers[i];  
  66.         }  
  67.     }  
  68. public:  
  69.     CMyData* pointers[3];  
  70. };  
  71.   
  72.   
  73. void TestPointerArchive()  
  74. {  
  75.     std::string content;  
  76.     {  
  77.         CMyData d1(1, "a");  
  78.         CMyData_Child d2(2, "b", 1.5);  
  79.   
  80.         CMyData_Container containter;  
  81.         containter.pointers[0] = &d1;  
  82.         containter.pointers[1] = &d2;  
  83.         containter.pointers[2] = &d1;  
  84.   
  85.         std::ostringstream os;  
  86.         boost::archive::binary_oarchive oa(os);  
  87.         oa << containter;  
  88.   
  89.         content = os.str();  
  90.     }  
  91.   
  92.     //·´ÐòÁл¯  
  93.     {  
  94.         CMyData_Container container;  
  95.         std::istringstream is(content);  
  96.         boost::archive::binary_iarchive ia(is);  
  97.         ia >> container;  
  98.   
  99.         for (int i = 0; i < 3; i++)  
  100.         {  
  101.             CMyData* d = container.pointers[i];  
  102.             std::cout << "pointer" << i + 1 <<": " << d->GetText() << "\n";  
  103.   
  104.             if (i == 1)  
  105.             {  
  106.                 CMyData_Child* child = reinterpret_cast<CMyData_Child*>(d);  
  107.                 std::cout << "pointer" << i + 1 <<", number: " << child->GetNumber() << "\n";  
  108.             }  
  109.         }  
  110.     }  
  111. }  


這次我們可以正確的讀取到第二個指針指向的對象了,可以看到_number的爭取值了。

把代碼和上個版本想比較,我們會發現2個不同:

1. CMyData類裏面多了個虛的析構函數;

2. 調用BOOST_CLASS_EXPORT_GUID給派生類CMyData_Child綁定一個字符串。

第二點很容易理解,就是給某個派生類命名一下,這樣就可以當作一個key來找到相應的類。那麼第一點爲什麼要增加一個虛析構函數呢?是我無意中添加的嗎?當然不是,其實這個是序列化指向派生類的指針的其中一個關鍵。先看Boost網站上面的一段描述:

It turns out that the kind of object serialized depends upon whether the base class (base in this case) is polymophic or not. Ifbase is not polymorphic, that is if it has no virtual functions, then an object of the typebasewill be serialized. Information in any derived classes will be lost. If this is what is desired (it usually isn't) then no other effort is required.

If the base class is polymorphic, an object of the most derived type (derived_oneorderived_twoin this case) will be serialized.  The question of which type of object is to be serialized is (almost) automatically handled by the library.

ok,通過這段描述,我們發現Boost序列化庫會判斷基類是不是多態的。判斷的依據就是這個基類裏面有沒有虛函數。我們知道,當一個類裏面有虛函數的時候,C++編譯器會自動給這個類增加一個成員:_vfptr,就是虛函數表指針。我沒有花太多時間去看Boost有關這部分的源代碼,但是我猜測Boost是根據這個_vfptr來判斷是需要序列化基類,還是派生類的。我們增加一個虛析構函數的目的也就是讓CMyData產生一個_vfptr。我們可以試一下把上面的代碼裏面的析構函數改成非虛的,那麼派生類序列化就會失敗,跟上一個章節得到相同的結果。至於Boost怎麼知道該序列化哪個派生類,相信這個是BOOST_CLASS_EXPORT_GUID的功勞,至於怎麼實現,還是需要看源代碼,但是我自己沒有仔細研究過,有興趣的朋友可以學習Boost的源代碼。Boost的設計很巧妙,我們可以學到不少東西。當然這個得有時間細細學習。好了,序列化指向派生類指針就2個要點:

1. 讓Boost知道基類是多態的,其實就是確保基類裏面有個虛函數;

2. 通過BOOST_CLASS_EXPORT_GUID給派生類綁定一個字符串,當作一個key。

 

至於第一種序列化指向派生類的基類指針:registration,可以參考http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/serialization.html#derivedpointers,上面講的非常清楚。我本人很少使用這種方式,這裏也就略過不講了。

 

序列化數組

一個小細節,上面講到的序列化指針章節裏面,我們看到代碼:

  1. class CMyData_Container  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         for(int i = 0; i < 3; i++)  
  10.         {  
  11.             ar & pointers[i];  
  12.         }  
  13.     }  
  14. public:  
  15.     CMyData* pointers[3];  
  16. };  

其中的序列化函數裏面有個for循環,難道每次序列化一個數組都需要弄一個for語句嗎,這個是不是可以改進呢?答案是肯定的。Boost自己會檢測數組。也就是說我們可以把代碼改成下面的形式:

  1. class CMyData_Container  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         ar & pointers;  
  10.     }  
  11. public:  
  12.     CMyData* pointers[3];  
  13. };  

代碼短了很多,方便吧。
 

 支持STL容器

 上面我們使用了一個普通數組來保存指針,我相信在平常寫程序過程中,大家都會使用STL容器,比如list,map,array等等。至少我自己是經常使用的。那麼Boost序列化庫可以序列化STL容器嗎?很幸運,Boost序列化庫已經支持了STL容器。原話是:

The above example uses an array of members.  More likely such an application would use an STL collection for such a purpose. The serialization library contains code for serialization of all STL classes.  Hence, the reformulation below will also work as one would expect.

 我們一開始就是用std::string作爲CMyData的一個成員,我們不需要做任何工作就可以直接序列化std::string,這是因爲Boost序列化庫已經支持std::string了。從上面的英文描述裏面可以看到Boost serialization庫可以支持所有STL類,神奇吧。至少我本人經常使用std::list, vector, map, string等,都可以正常工作。下面的代碼使用std::vector代替了普通數組,可以正常工作。

  1. class CMyData  
  2. {  
  3. private:  
  4.     friend class boost::serialization::access;  
  5.   
  6.     template<class Archive>  
  7.     void serialize(Archive& ar, const unsigned int version)  
  8.     {  
  9.         ar & _tag;  
  10.         ar & _text;  
  11.     }  
  12.   
  13.       
  14. public:  
  15.     CMyData():_tag(0), _text(""){}  
  16.   
  17.     CMyData(int tag, std::string text):_tag(tag), _text(text){}  
  18.     virtual ~CMyData(){}  
  19.   
  20.     int GetTag() const {return _tag;}  
  21.     std::string GetText() const {return _text;}  
  22.   
  23. private:  
  24.     int _tag;  
  25.     std::string _text;  
  26. };  
  27.   
  28. class CMyData_Child: public CMyData  
  29. {  
  30. private:  
  31.     friend class boost::serialization::access;  
  32.   
  33.     template<class Archive>  
  34.     void serialize(Archive& ar, const unsigned int version)  
  35.     {  
  36.         // serialize base class information  
  37.         ar & boost::serialization::base_object<CMyData>(*this);  
  38.         ar & _number;  
  39.     }  
  40.   
  41.   
  42. public:  
  43.     CMyData_Child():_number(0.0){}  
  44.   
  45.     CMyData_Child(int tag, std::string text, float number):CMyData(tag, text), _number(number){}  
  46.   
  47.     float GetNumber() const{return _number;}  
  48.   
  49. private:  
  50.     float _number;  
  51. };  
  52.   
  53. BOOST_CLASS_EXPORT_GUID(CMyData_Child, "CMyData_Child")  
  54.   
  55. //ʹÓÃSTLÈÝÆ÷  
  56. class CMyData_ContainerSTL  
  57. {  
  58. private:  
  59.     friend class boost::serialization::access;  
  60.   
  61.     template<class Archive>  
  62.     void serialize(Archive& ar, const unsigned int version)  
  63.     {  
  64.         ar & vPointers;  
  65.     }  
  66. public:  
  67.     std::vector<CMyData*> vPointers;  
  68. };  
  69.   
  70.   
  71.   
  72. void TestPointerArchiveWithSTLCollections()  
  73. {  
  74.     std::string content;  
  75.     {  
  76.         CMyData d1(1, "parent obj");  
  77.         CMyData_Child d2(2, "child obj", 2.5);  
  78.   
  79.         CMyData_ContainerSTL containter;  
  80.         containter.vPointers.push_back(&d1);  
  81.         containter.vPointers.push_back(&d2);  
  82.         containter.vPointers.push_back(&d1);  
  83.           
  84.   
  85.         std::ostringstream os;  
  86.         boost::archive::binary_oarchive oa(os);  
  87.         oa << containter;  
  88.   
  89.         content = os.str();  
  90.     }  
  91.   
  92.     //·´ÐòÁл¯  
  93.     {  
  94.         CMyData_ContainerSTL container;  
  95.         std::istringstream is(content);  
  96.         boost::archive::binary_iarchive ia(is);  
  97.         ia >> container;  
  98.   
  99.         std::cout<<"Test STL collections:\n";  
  100.         BOOST_FOREACH(CMyData* p, container.vPointers)  
  101.         {  
  102.             std::cout << "object text: " << p->GetText() << "\n";  
  103.   
  104.             CMyData_Child* child = dynamic_cast<CMyData_Child*>(p);  
  105.             if (child)  
  106.             {  
  107.                 std::cout << "child object number: " << child->GetNumber() << "\n";  
  108.             }  
  109.         }  
  110.     }  
  111. }  

一不小心就用到了BOOST_FOREACH,看來這個確實很好用啊,呵呵。省去了寫很長的iterator來遍歷整個vector。

 

class版本
再來考慮一個問題,比方說現在我們程序升級了,然後把某個類給升級了一下,加了一個成員,那麼之前保存的序列化的數據還能匹配到新的類嗎?看一下序列化函數,我們會發現這個序列化函數有個參數,叫做version

template<class Archive>
 void serialize(Archive& ar, const unsigned int version)

通過這個參數,我們就可以解決class版本的問題。看這段描述

In general, the serialization library stores a version number in the archive for each class serialized.  By default this version number is 0. When the archive is loaded, the version number under which it was saved is read.

也就是說如果我們不刻意指定version,那麼Boost序列化庫就會默認設置爲0並且保存到序列化結果中。

如果我們要標記不同的class版本,可以使用宏BOOST_CLASS_VERSION,比如

BOOST_CLASS_VERSION(CMyData, 1)

 具體這裏就不舉例了。參考Boost說明。

 

save和load分開

 一直到現在我們都是用了一個序列化函數

template<class Archive>
 void serialize(Archive& ar, const unsigned int version)

其實,序列化包括序列化和發序列化兩部分,或者稱之爲save和load,甚至mashalling,unmarshalling。反正就這個意思。

還有一個奇怪的地方,就是通常我們輸入輸出是用<<和>>的,那麼在函數serialize裏面我們用了&。其實這個是Boost對&做了一個封裝。假如現在是做序列化,那麼&就等同於<<,假如是反序列化,那麼&就等同於>>。然後序列化和反序列化統統用一個函數serialize來實現。這也體現了Boost的巧妙設計。

那麼如果有特殊需求,我們需要把序列化和反序列化分開,應該怎麼實現呢?

就好比上面的class版本問題,save和load可能就是不一樣的,因爲load需要考慮兼容舊的版本。這裏就偷懶使用Boost文檔上的例子了。我們可以看到save和load是分開的。

  1. #include <boost/serialization/list.hpp>  
  2. #include <boost/serialization/string.hpp>  
  3. #include <boost/serialization/version.hpp>  
  4. #include <boost/serialization/split_member.hpp>  
  5.   
  6. class bus_route  
  7. {  
  8.     friend class boost::serialization::access;  
  9.     std::list<bus_stop *> stops;  
  10.     std::string driver_name;  
  11.     template<class Archive>  
  12.     void save(Archive & ar, const unsigned int version) const  
  13.     {  
  14.         // note, version is always the latest when saving  
  15.         ar  & driver_name;  
  16.         ar  & stops;  
  17.     }  
  18.     template<class Archive>  
  19.     void load(Archive & ar, const unsigned int version)  
  20.     {  
  21.         if(version > 0)  
  22.             ar & driver_name;  
  23.         ar  & stops;  
  24.     }  
  25.     BOOST_SERIALIZATION_SPLIT_MEMBER()  
  26. public:  
  27.     bus_route(){}  
  28. };  
  29.   
  30. BOOST_CLASS_VERSION(bus_route, 1)  

注意需要使用宏BOOST_SERIALIZATION_SPLIT_MEMBER()來告訴Boost序列化庫使用save和load代替serialize函數。

到這裏,我們幾乎把Boost序列化庫所有的內容都介紹完畢了。這個庫是相當的nice,基本可以cover所有的case。而且就開源庫來講,Boost的說明文檔真的算是很好的了。基本上都有詳細的說明,就序列化庫而言,直接看這個頁面就基本ok了,http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/tutorial.html 相當的詳細。儘管讀英文比較累,但是可以獲得原汁原味的第一手權威資料,花這些功夫還是值得的。

我的例子裏面使用了二進制流來保存序列化後的數據,其實還有其他的archive格式,比如text,XML等等。甚至我們可以自己來實現序列化格式。Boost已經定義了一個統一的接口,我們要實現自己的格式,只需要繼承相應的Boost::archive裏面的類就可以了。

好了,寫完了,希望對大家有點幫助。如有錯誤,歡迎指出。

 

附,完整測試代碼,使用這段代碼前需要確保VISUAL STUDIO已經設置了Boost的路徑。

  1. // Serialization.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5.   
  6. #include "boost/serialization/serialization.hpp"  
  7. #include "boost/archive/binary_oarchive.hpp"  
  8. #include "boost/archive/binary_iarchive.hpp"  
  9. #include <boost/serialization/export.hpp>  
  10. #include "boost/foreach.hpp"  
  11. #include "boost/any.hpp"  
  12. #include <boost/serialization/vector.hpp>  
  13.   
  14.   
  15.   
  16. #include <string>  
  17. #include <Windows.h>  
  18. #include <iostream>  
  19. #include <sstream>  
  20. #include <vector>  
  21.   
  22.   
  23. //測試序列化  
  24. class CMyData  
  25. {  
  26. private:  
  27.     friend class boost::serialization::access;  
  28.   
  29.     template<class Archive>  
  30.     void serialize(Archive& ar, const unsigned int version)  
  31.     {  
  32.         ar & _tag;  
  33.         ar & _text;  
  34.     }  
  35.   
  36.       
  37. public:  
  38.     CMyData():_tag(0), _text(""){}  
  39.   
  40.     CMyData(int tag, std::string text):_tag(tag), _text(text){}  
  41.     virtual ~CMyData(){}  
  42.   
  43.     int GetTag() const {return _tag;}  
  44.     std::string GetText() const {return _text;}  
  45.   
  46. private:  
  47.     int _tag;  
  48.     std::string _text;  
  49. };  
  50.   
  51.   
  52. void TestArchive1()  
  53. {  
  54.     std::string content;  
  55.   
  56.     {  
  57.         CMyData d1(2012, "China, good luck");  
  58.         std::ostringstream os;  
  59.         boost::archive::binary_oarchive oa(os);  
  60.         oa << d1;//序列化到一個ostringstream裏面  
  61.   
  62.         content = os.str();//content保存了序列化後的數據。  
  63.     }  
  64.       
  65.   
  66.     {  
  67.         CMyData d2;  
  68.         std::istringstream is(content);  
  69.         boost::archive::binary_iarchive ia(is);  
  70.         ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  71.   
  72.         std::cout << "CMyData tag: " << d2.GetTag() << ", text: " << d2.GetText() << "\n";  
  73.     }  
  74.       
  75. }  
  76.   
  77.   
  78. class CMyData2  
  79. {  
  80. public:  
  81.     CMyData2():_tag(0), _text(""){}  
  82.   
  83.     CMyData2(int tag, std::string text):_tag(tag), _text(text){}  
  84.   
  85.     int _tag;  
  86.     std::string _text;  
  87. };  
  88.   
  89. namespace boost {  
  90.     namespace serialization {  
  91.   
  92.         template<class Archive>  
  93.         void serialize(Archive & ar, CMyData2 & d, const unsigned int version)  
  94.         {  
  95.             ar & d._tag;  
  96.             ar & d._text;  
  97.         }  
  98.   
  99.     } // namespace serialization  
  100. // namespace boost  
  101.   
  102. void TestArchive2()  
  103. {  
  104.     CMyData2 d1(2012, "China, good luck");  
  105.     std::ostringstream os;  
  106.     boost::archive::binary_oarchive oa(os);  
  107.     oa << d1;//序列化到一個ostringstream裏面  
  108.   
  109.     std::string content = os.str();//content保存了序列化後的數據。  
  110.   
  111.     CMyData2 d2;  
  112.     std::istringstream is(content);  
  113.     boost::archive::binary_iarchive ia(is);  
  114.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  115.   
  116.     std::cout << "CMyData2 tag: " << d2._tag << ", text: " << d2._text << "\n";  
  117. }  
  118.   
  119.   
  120. //序列化子類,侵入式  
  121. class CMyData_Child: public CMyData  
  122. {  
  123. private:  
  124.     friend class boost::serialization::access;  
  125.   
  126.     template<class Archive>  
  127.     void serialize(Archive& ar, const unsigned int version)  
  128.     {  
  129.         // serialize base class information  
  130.         ar & boost::serialization::base_object<CMyData>(*this);  
  131.         ar & _number;  
  132.     }  
  133.   
  134.   
  135. public:  
  136.     CMyData_Child():_number(0.0){}  
  137.   
  138.     CMyData_Child(int tag, std::string text, float number):CMyData(tag, text), _number(number){}  
  139.   
  140.     float GetNumber() const{return _number;}  
  141.   
  142. private:  
  143.     float _number;  
  144. };  
  145.   
  146. BOOST_CLASS_EXPORT_GUID(CMyData_Child, "CMyData_Child")  
  147.   
  148.   
  149. void TestArchive3()  
  150. {  
  151.     CMyData_Child d1(2012, "China, good luck", 1.2);  
  152.     std::ostringstream os;  
  153.     boost::archive::binary_oarchive oa(os);  
  154.     oa << d1;//序列化到一個ostringstream裏面  
  155.   
  156.     std::string content = os.str();//content保存了序列化後的數據。  
  157.   
  158.     CMyData_Child d2;  
  159.     std::istringstream is(content);  
  160.     boost::archive::binary_iarchive ia(is);  
  161.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  162.   
  163.     std::cout << "CMyData_Child tag: " << d2.GetTag() << ", text: " << d2.GetText() << ", number: "<<d2.GetNumber() << "\n";  
  164. }  
  165.   
  166. //序列化子類,非侵入式  
  167. class CMyData2_Child: public CMyData2  
  168. {  
  169. public:  
  170.     CMyData2_Child():_number(0.0){}  
  171.   
  172.     CMyData2_Child(int tag, std::string text, float number):CMyData2(tag, text), _number(number){}  
  173.   
  174.     float _number;  
  175. };  
  176.   
  177. namespace boost {  
  178.     namespace serialization {  
  179.   
  180.         template<class Archive>  
  181.         void serialize(Archive & ar, CMyData2_Child & d, const unsigned int version)  
  182.         {  
  183.             // serialize base class information  
  184.             ar & boost::serialization::base_object<CMyData2>(d);  
  185.             ar & d._number;  
  186.         }  
  187.   
  188.     } // namespace serialization  
  189. // namespace boost  
  190.   
  191. void TestArchive4()  
  192. {  
  193.     CMyData2_Child d1(2012, "test non-intrusive child class", 5.6);  
  194.     std::ostringstream os;  
  195.     boost::archive::binary_oarchive oa(os);  
  196.     oa << d1;//序列化到一個ostringstream裏面  
  197.   
  198.     std::string content = os.str();//content保存了序列化後的數據。  
  199.   
  200.     CMyData2_Child d2;  
  201.     std::istringstream is(content);  
  202.     boost::archive::binary_iarchive ia(is);  
  203.     ia >> d2;//從一個保存序列化數據的string裏面反序列化,從而得到原來的對象。  
  204.   
  205.     std::cout << "CMyData2_Child tag: " << d2._tag << ", text: " << d2._text << ", number: "<<d2._number<<"\n";  
  206. }  
  207.   
  208.   
  209. //指針數據成員  
  210.   
  211. class CMyData_Container  
  212. {  
  213. private:  
  214.     friend class boost::serialization::access;  
  215.   
  216.     template<class Archive>  
  217.     void serialize(Archive& ar, const unsigned int version)  
  218.     {  
  219.         ar & pointers;  
  220.     }  
  221. public:  
  222.     CMyData* pointers[3];  
  223. };  
  224.   
  225.   
  226.   
  227. void TestPointerArchive()  
  228. {  
  229.     std::string content;  
  230.     {  
  231.         CMyData d1(1, "a");  
  232.         CMyData_Child d2(2, "b", 1.5);  
  233.   
  234.         CMyData_Container containter;  
  235.         containter.pointers[0] = &d1;  
  236.         containter.pointers[1] = &d2;  
  237.         containter.pointers[2] = &d1;  
  238.   
  239.         std::ostringstream os;  
  240.         boost::archive::binary_oarchive oa(os);  
  241.         oa << containter;  
  242.   
  243.         content = os.str();  
  244.     }  
  245.   
  246.     //反序列化  
  247.     {  
  248.         CMyData_Container container;  
  249.         std::istringstream is(content);  
  250.         boost::archive::binary_iarchive ia(is);  
  251.         ia >> container;  
  252.   
  253.         for (int i = 0; i < 3; i++)  
  254.         {  
  255.             CMyData* d = container.pointers[i];  
  256.             std::cout << "pointer" << i + 1 <<": " << d->GetText() << "\n";  
  257.   
  258.             if (i == 1)  
  259.             {  
  260.                 CMyData_Child* child = reinterpret_cast<CMyData_Child*>(d);  
  261.                 std::cout << "pointer" << i + 1 <<", number: " << child->GetNumber() << "\n";  
  262.             }  
  263.         }  
  264.     }  
  265. }  
  266.   
  267. //使用STL容器  
  268. class CMyData_ContainerSTL  
  269. {  
  270. private:  
  271.     friend class boost::serialization::access;  
  272.   
  273.     template<class Archive>  
  274.     void serialize(Archive& ar, const unsigned int version)  
  275.     {  
  276.         ar & vPointers;  
  277.     }  
  278. public:  
  279.     std::vector<CMyData*> vPointers;  
  280. };  
  281.   
  282.   
  283.   
  284. void TestPointerArchiveWithSTLCollections()  
  285. {  
  286.     std::string content;  
  287.     {  
  288.         CMyData d1(1, "parent obj");  
  289.         CMyData_Child d2(2, "child obj", 2.5);  
  290.   
  291.         CMyData_ContainerSTL containter;  
  292.         containter.vPointers.push_back(&d1);  
  293.         containter.vPointers.push_back(&d2);  
  294.         containter.vPointers.push_back(&d1);  
  295.           
  296.   
  297.         std::ostringstream os;  
  298.         boost::archive::binary_oarchive oa(os);  
  299.         oa << containter;  
  300.   
  301.         content = os.str();  
  302.     }  
  303.   
  304.     //反序列化  
  305.     {  
  306.         CMyData_ContainerSTL container;  
  307.         std::istringstream is(content);  
  308.         boost::archive::binary_iarchive ia(is);  
  309.         ia >> container;  
  310.   
  311.         std::cout<<"Test STL collections:\n";  
  312.         BOOST_FOREACH(CMyData* p, container.vPointers)  
  313.         {  
  314.             std::cout << "object text: " << p->GetText() << "\n";  
  315.   
  316.             CMyData_Child* child = dynamic_cast<CMyData_Child*>(p);  
  317.             if (child)  
  318.             {  
  319.                 std::cout << "child object number: " << child->GetNumber() << "\n";  
  320.             }  
  321.         }  
  322.     }  
  323. }  
  324.   
  325. int _tmain(int argc, _TCHAR* argv[])  
  326. {  
  327.     TestArchive1();  
  328.   
  329.     TestArchive2();  
  330.   
  331.     TestArchive3();  
  332.   
  333.     TestArchive4();  
  334.   
  335.     TestPointerArchive();  
  336.   
  337.     TestPointerArchiveWithSTLCollections();  
  338.   
  339.     return 0;  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章