【发布时间】:2014-02-21 10:05:05
【问题描述】:
“每当我们在指针(或引用)上调用序列化时,它都会在必要时触发它指向(或引用)的对象的序列化” - A practical guide to C++ serialization at codeproject.com文章有一个很好的解释来演示如何序列化指针也序列化指针指向的数据,所以我写了一个代码来试试这个:
#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;
我在这里遇到了分段错误!谁能告诉我如何让这个工作?非常感谢!
【问题讨论】:
标签: c++ class boost boost-serialization