Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructor for boost::property_tree::ptree

Tags:

c++

boost

I use boost::property_tree::ptree quite a bit, but I've found that I create, pass around, and then save copies too many times. With big ptree objects this is expensive.

Boost provides a swap function, but no move constructor. Why would they do that?

My current solution is to extend ptree and make one myself:

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

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

Is this the best solution or am I missing something?

like image 514
Stewart Avatar asked Mar 10 '26 13:03

Stewart


2 Answers

I think your solution is pretty decent. Note that it will never affect internal tree operations, as the tree will see its children as ptree, not MyPtree.

Slightly better is to propose the new feature and suggest it to de library devs.


Related is Is there a convenient way to erase a node from a property tree, preserving its child nodes?.

If you want to dig deeper, you'll find that Property Tree builds on Boost MultiIndex which, for various reasons, doesn't seemless allow moving from values: Move element from boost multi_index array

You could add a splice() operation building on the list-ness of the various indexes used:

For now, ptree could add a splice operation, which would naturally wrap multi_index's list operations: I just made a draft implementation sehe - Sep 23 '17 at 9:48

like image 152
sehe Avatar answered Mar 12 '26 04:03

sehe


Stewart, I've seen the ptree destructor and it seems that it's not virtual. It means the base destructor (ptree) will not be invoked if MyPtree is used polymorphically. Maybe you should consider to use composition instead of inheritance. See this answer enter image description here

This might be a sketch:

class MyPtree
{
   boost::property_tree::ptree m_tree;

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

  ... plus adding the other constructors and operators
};
like image 31
elarmando Avatar answered Mar 12 '26 02:03

elarmando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!