c++ - 使用 boost::serialization 的序列化树结构

标签 c++ serialization tree boost-serialization

我必须在我的程序中序列化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/

相关文章:

c++ - Torus 的纹理应用不正确

c++ - 从字符串中删除字符

java - 如何序列化和恢复函数列表?

java - Jackson2ObjectMapperBuilder 不序列化对象

java - 递归搜索二叉树问题

java - 按层次结构对类进行排序的树

c++ - 为什么 char* 和 int* 表现不同

c++ - 网络 bean : Adding "Compile Line - Additional Options" "-lboost_system" at the end of compile command

java - 为什么Java序列化占用这么大的空间?

c - 警告 - Expected ‘struct node **’ but argument is of type ‘struct node **’ 是什么意思?