“每当我们在指针(或引用)上调用序列化时,都会在必要时触发它指向(或引用)的对象的序列化”- A practical guide to C++ serialization在 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;
我在这里遇到了段错误!谁能告诉我如何让它工作?非常感谢!
最佳答案
您将对象写入流,而不是存档:)
boost::archive::text_oarchive def(abc);
abc << point_first;
尝试
def << point_first;
相反。结果:
22 serialization::archive 10 0 1 0
0 20 12.56
关于c++ - 指针的 boost 序列化保存指针的十六进制值而不是对象的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21931134/