測試了下boost的序列化反序列化功能
阿新 • • 發佈:2017-10-07
con != bar lan class try hat out ora
[cpp] view plain copy
- // testSerialization.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <boost/archive/text_oarchive.hpp>
- #include <boost/archive/text_iarchive.hpp>
- #include <boost/serialization/vector.hpp>
- #include <string>
- #include <vector>
- #include <iostream>
- #include <sstream>
- #include <fstream>
- /*
- 標題:boost的序列化反序列化功能測試
- 環境:VS2010sp1、boost 1.55
- 參考資料:
- [1]《Boost中支持序列化反序列化的庫--boost.serialization 》
- http://blog.csdn.net/oracleot/article/details/4280084
- [2]《What does BOOST_SERIALIZATION_NVP do when serializing object?》
- http://stackoverflow.com/questions/8532331/what-does-boost-serialization-nvp-do-when-serializing-object
- */
- struct MyRecord
- {
- std::string a;
- std::string b;
- //為使當前的結構能支持序列化,得加入下面的代碼段
- private:
- friend class boost::serialization::access;
- template<class Archive>
- void serialize(Archive & ar, const unsigned int version)
- {
- ar & a;
- ar & b;
- }
- };
- struct MyData{
- int id;
- std::string strName;
- std::string strValue;
- MyData() {}
- MyData(int id, std::string strName, std::string strValue)
- {
- this->id = id;
- this->strName = strName;
- this->strValue = strValue;
- }
- std::vector<MyRecord> listMR;
- private:
- friend boost::serialization::access; //聲明友元,授予訪問權限
- template<typename Archive>
- void serialize(Archive &ar,const unsigned int version) //序列化函數
- {
- ar & id;
- ar & strName & strValue;
- ar & listMR;
- }
- };
- void printTest(MyData &mt)
- {
- std::cout<<"a="<<mt.id<<" uid="<<mt.strName.c_str()<<" usr="<<mt.strValue.c_str()<<std::endl;
- std::vector<MyRecord>::iterator iter = mt.listMR.begin();
- while(iter!=mt.listMR.end())
- {
- std::cout<<"=> "<<iter->a.c_str()<<" "<<iter->b.c_str()<<std::endl;
- iter++;
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- std::stringstream ss;
- //序列化
- MyData p1(11,"anderson","neo"); //被序列化的對象
- //為被序列化對象添加兩條記錄
- MyRecord mr,mr2;
- mr.a="apple",mr.b="第一條記錄";
- mr2.a = "this is b",mr2.b = "第二條記錄";
- p1.listMR.push_back(mr);
- p1.listMR.push_back(mr2);
- boost::archive::text_oarchive(ss) << p1; //序列化
- //序列化為xml形式要求中文為utf-8編碼,否則打開文件是亂碼
- //std::stringstream ss;
- //std::ofstream ofs("d:\\a.xml");
- //boost::archive::xml_oarchive oa(ofs);
- //oa << BOOST_SERIALIZATION_NVP(p1);
- //反序列化
- MyData p2; //被反序列化的對象
- boost::archive::text_iarchive(ss) >> p2; //反序列化
- printTest(p2);
- std::cout << "序列化後的=>" << ss.str() << std::endl;;
- return 0;
- }
http://blog.csdn.net/lee353086/article/details/38421095
測試了下boost的序列化反序列化功能