我必须在我的程序中序列化libkdtree++,树结构简要描述如下:
struct _Node_base {
_Node_base * _M_parent, *_M_left, * _M_right;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & _M_left & _M_right;
}
}
template<typename V>
struct _Node : public _Node_base {
typedef V value_type;
value_type value;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar.register_type(static_cast<_Node*>(NULL));
ar & boost::serialization::base_object<_Node_base>(*this);
ar & value;
}
}
struct Tree {
_Node * root;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & root;
}
}
该程序报告“流错误”。 但是从“序列化文件”来看,它缺少根的子节点的值字段。因此我认为 BaseNode 可能序列化了 _M_left 和 _M_right 指针。然而,由于_Node_base 不知道_Node 的值类型,因此很难将“ar.register_type”添加到_Node_base.serialize()。
最佳答案
pointer_conflict 异常 documentation州(原文如此):
pointer_conflict, // an attempt has been made to directly
// serialization::detail an object
// after having already serialzed the same
// object through a pointer. Were this permited,
// it the archive load would result in the
// creation of an extra copy of the obect.
我认为冲突发生在 BaseNode::serialize
中的 ptr 和 Node 中的直接对象
。但是,由于 *Node
表达式序列化的地方::序列化base_object
函数采用引用而不是 ptr,我不确定您将如何避免这种情况。
一种可能性是不序列化 parent
ptr。相反,在反序列化之后,遍历树并修复父指针以指向节点父节点。例如。将以下方法添加到 BaseNode :
void fix (BaseNode* parent = 0)
{
this->parent = parent;
if (left != 0)
left->fix (this);
if (right != 0)
right->fix (this);
}
然后只要调用root->fix()
关于c++ - 使用 boost::serialization 的序列化树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315963/