我定义了以下要序列化的类:
using namespace std;
class MyElementObject
{
friend class boost::serialization::access;
public:
template<class Archive>
void serialize(Archive & ar, const unsigned int version) { }
};
template<class T>
class MyRecursiveObject
{
friend class boost::serialization::access;
public:
T element;
std::vector<MyRecursiveObject<T> > children;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & element;
ar & children;
}
};
然后我运行以下代码:
int main()
{
//MyRecursiveObject initialization
MyRecursiveObject<MyElementObject> rec_object;
rec_object.children.push_back(MyRecursiveObject<MyElementObject>());
rec_object.children[0].children.push_back(MyRecursiveObject<MyElementObject>());
//create vector of pointers to MyRecursiveObject's elements
vector<MyElementObject *> elt_ptrs;
elt_ptrs.push_back(&rec_object.element);
elt_ptrs.push_back(&rec_object.children[0].element);
elt_ptrs.push_back(&rec_object.children[0].children[0].element);
//serialize MyRecursiveObject and the vector of pointers
{
ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
oa << rec_object;
oa << elt_ptrs;
}
//create new MyRecursiveObject and vector of pointers for deserialization
MyRecursiveObject<MyElementObject> rec_object_deserialized;
rec_object_deserialized.children.push_back(MyRecursiveObject<MyElementObject>());
rec_object_deserialized.children[0].children.push_back(MyRecursiveObject<MyElementObject>());
vector<MyElementObject *> elt_ptrs_deserialized;
//deserialize
{
ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
ia >> rec_object_deserialized;
ia >> elt_ptrs_deserialized;
}
//compare deserialized pointers
cout<<"elt_ptrs first level="<<elt_ptrs_deserialized[0]
<<" expected="<<&rec_object_deserialized.element<<endl;
cout<<"elt_ptrs second level="<<elt_ptrs_deserialized[1]
<<" expected="<<&rec_object_deserialized.children[0].element<<endl;
cout<<"elt_ptrs third level="<<elt_ptrs_deserialized[2]
<<" expected="<<&rec_object_deserialized.children[0].children[0].element<<endl;
return 0;
}
我总是得到类似于以下的输出:
elt_ptrs first level=0x7fff57c787c0 expected=0x7fff57c787c0
elt_ptrs second level=0x18e7020 expected=0x18e7020
elt_ptrs third level=0xffff8000ab5564f0 expected=0x18e7450
从指针值可以看出,我设法将指向元素的指针反序列化到 MyRecursiveObject 的第二个递归级别。一旦我尝试使用指向第三级或更深层次的指针来执行此操作,反序列化就会失败。
我是否错误地使用了 boost::serialization?
请注意 MyRecursiveObject 总是成功反序列化,无论它有多少递归级别。我遇到的问题只是反序列化指向其元素的指针。
提前谢谢你,基恩