「每當我們調用指針(或引用)的序列化時,就會在必要時觸發它指向(或引用)的對象的序列化」 - A practical guide to C++ serialization在codeproject.com這篇文章有一個很好的解釋來說明如何序列化的指針也串行數據由指針指向,所以我寫了一個代碼來試試這個:指針的Boost序列化保存指針的十六進制值,而不是對象的內容
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class datta {
public:
int integers;
float decimals;
datta(){}
~datta(){}
datta(int a, float b) {
integers=a;
decimals=b;
}
void disp_datta() {
std::cout<<"\n int: "<<integers<<" float" <<decimals<<std::endl;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & integers;
ar & decimals;
}
};
int main() {
datta first(20,12.56);
datta get;
datta* point_first;
datta* point_get;
point_first=&first;
first.disp_datta();
std::cout<<"\n ptr to first :"<<point_first;
//Serialize
std::ofstream abc("file.txt");
{
boost::archive::text_oarchive def(abc);
abc << point_first;
}
return 0;
}
運行此代碼後,我打開file.txt並找到一個十六進制指針地址,而不是這個地址指向的值,我也寫了一個反序列化代碼:
std::ifstream zxc("file.txt");
{
boost::archive::text_iarchive ngh(zxc);
ngh >> point_get;
}
//Dereference the ptr and
get = *point_get;
get.disp_datta();
std::cout<<"\n ptr to first :"<<point_get;
我在這裏遇到了分段錯誤!任何人都可以告訴我如何讓這個工作?非常感謝!
對於指針反序列化,使用-lboost_system標誌是必要的嗎? – chetan92
我試圖運行它沒有國旗,它仍然正常工作。 – chetan92
最後設法運行它。非常感謝!人類信仰(或計算)恢復! – chetan92