boost::property_tree::ptree的移动构造函数

3
我经常使用 boost::property_tree::ptree,但我发现我创建、传递和保存副本的次数太多了。对于大型的ptree对象来说,这是很昂贵的。

Boost 提供了一个swap函数,但没有移动构造函数。他们为什么要这样做呢?

我的当前解决方案是扩展ptree并自己创建一个:

class MyPtree : public boost::property_tree::ptree
{
  MyPtree(MyPtree&& other)
  {
    swap(other);
  }

  ... plus adding the other constructors and operators
};

这是最好的解决方案吗?还是我漏掉了什么?


2
他们为什么要这样做?因为他们没有更新到C++11。 - UKMonkey
3个回答

2
我认为你的解决方案相当不错。请注意,它永远不会影响内部树操作,因为树将其子项视为ptree而不是MyPtree
稍微好一点的方法是提出新功能并建议将其提交给库维护人员。
相关问题:是否有方便的方法从属性树中删除节点并保留其子节点?
如果您想深入挖掘,您会发现Property Tree构建在Boost MultiIndex之上,由于各种原因,Boost MultiIndex似乎不允许无缝移动值:从boost multi_index数组中移动元素
您可以添加一个基于使用的各种索引的列表性质构建的splice()操作:

目前,ptree可以添加一个splice操作,它将自然包装multi_index的列表操作:我刚刚制作了草案实现sehe - Sep 23 '17 at 9:48


1
Stewart,我看到了ptree析构函数,它似乎不是虚拟的。这意味着如果以多态方式使用MyPtree,则不会调用基类析构函数(ptree)。也许您应该考虑使用组合而不是继承。请参见此答案 enter image description here
这可能是一个草图:
class MyPtree
{
   boost::property_tree::ptree m_tree;

   MyPtree(MyPtree&& other)
   {
      m_tree.swap(other.m_tree);
   }

  ... plus adding the other constructors and operators
};

1
@JHBonarius,我添加了一段代码示例,你觉得怎么样? - elarmando
通常从一个没有虚析构函数的类派生是没问题的。只有当派生类的析构函数需要做比基类更多的事情,并且你使用指向基类的指针删除派生类型的对象时,才会遇到麻烦... - Marc Glisse
这意味着当MyPtree被销毁时,基本析构函数(ptree)将不会被调用。但这完全是无稽之谈。 - T.C.

0

使用组合而非继承

class MyPtree
{
public:
  MyPtree():{m_tree_ptr = new boost::property_tree::ptree();
  MyPtree(MyPtree&& other){m_tree_ptr = other.m_tree_ptr; other.m_tree_ptr = nullptr;}
  ~MyPtree(){if (m_tree_ptr != nullptr) delete m_tree_ptr;}
  // copy conctructor and assign operator

private:
 boost::property_tree::ptree* m_tree_ptr;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接