Added copy constructor and assignment operator using C++11 move semantics

This commit is contained in:
Bart Trzynadlowski 2016-08-19 00:01:45 +00:00
parent a9816467d8
commit 01a6ad1596
3 changed files with 26 additions and 1 deletions

View file

@ -217,12 +217,28 @@ namespace Util
}
}
void Node::Swap(Node &rhs)
{
m_next_sibling.swap(rhs.m_next_sibling);
m_first_child.swap(rhs.m_first_child);
m_last_child.swap(rhs.m_last_child);
m_children.swap(rhs.m_children);
const_cast<std::string *>(&m_key)->swap(*const_cast<std::string *>(&rhs.m_key));
m_value.swap(rhs.m_value);
}
Node &Node::operator=(const Node &rhs)
{
DeepCopy(rhs);
return *this;
}
Node &Node::operator=(Node &&rhs)
{
Swap(rhs);
return *this;
}
Node::Node()
{
//std::cout << "<<< Created " << "<null>" << " (" << this << ")" << std::endl;
@ -248,11 +264,17 @@ namespace Util
DeepCopy(that);
}
Node::Node(Node &&that)
{
Swap(that);
}
Node::~Node()
{
//std::cout << ">>> Destroyed " << m_key << " (" << this << ")" << std::endl;
}
// An explicit function so that users don't accidentally create empty nodes
Node::Ptr_t CreateEmpty()
{
return std::shared_ptr<Node>(new Node());

View file

@ -36,6 +36,7 @@ namespace Util
void AddChild(Node &parent, Ptr_t &node);
void DeepCopy(const Node &that);
void Swap(Node &rhs);
Node(); // prohibit accidental/unintentional creation of blank nodes
friend Ptr_t CreateEmpty();
@ -210,9 +211,11 @@ namespace Util
Node &Add(const std::string &key, const std::string &value = "");
void Set(const std::string &key, const std::string &value);
Node &operator=(const Node &rhs);
Node &operator=(Node &&rhs);
Node(const std::string &key);
Node(const std::string &key, const std::string &value);
Node(const Node &that);
Node(Node &&that);
~Node();
};

View file

@ -70,7 +70,7 @@ int main()
std::cout << std::endl;
test_results.push_back({ "Copy constructed", copy->ToString() == root->ToString() });
// Make a copy using assignment operator
// Make a deep copy using assignment operator
std::cout << "Copy by assignment:" << std::endl << std::endl;
Util::Config::Node copy2("foo", "bar");
copy2.Add("x/y/z", "test");