Reputation: 95
I am trying to overload the assignment operator for my Binary Search Tree.
Example: tree1 = tree2
I want to delete all the nodes in tree1 and make deep copy of all nodes in tree.
I already have function:
Node* deepCopyTree(const Node *source)
which works perfectly well. I created also this function:
void deleteTree(Node* root)
{
if (root)
{
deleteTree(root->left);
deleteTree(root->right);
delete root;
}
}
which as I see my debugging it works. The operator overload function :
BST& BST::operator=(const BST &rhs)
{
DestroyRecursive(root);
deepCopyTree(rhs.root);
return *this;
}
And that throws me an error when copying.. I am working from 10 hours on that and this is the smallest thing I have left with and I want to finish it. Please help :) .
That is my deep copy constructor:
BST::BST(const bST&rhs)
:root(deepCopyTree(rhs.root))
{
}
deepCopyTree returns Node*
struct Node
{
std::string value = "";
Node *left = nullptr;
Node *right = nullptr;
};
Deconstructor:
BST::~BST()
{
DeleteTree(this->root);
}
void DeleteTree(Node* root)
{
if (root)
{
DeleteTree(root->left);
DeleteTree(root->right);
delete root;
}
}
Upvotes: 1
Views: 4761
Reputation: 35440
Provided that the copy constructor and destructor for BST
work correctly (and that the copy constructor does not use the assignment operator), the BST
assignment operator can be easily written using the copy/swap idiom:
#include <algorithm>
//...
BST& BST::operator=(const BST &rhs)
{
if ( &rhs != this ) // for optimization purposes, check for self assignment
{
BST temp(rhs); // copy the rhs (uses copy constructor)
std::swap(temp.root, root); // swap out the members (root with temp.root)
} // temp now dies off with the old data (uses destructor)
return *this;
}
Note that all we did was create a temporary (which is why the copy constructor has to work properly). Then swap out the this
members with the temporary's members. Once this is done, when temp
is destroyed, it takes the old data with it (which is why the destructor has to work properly).
If there are more members, then you need to swap those out also (I am assuming the only member variable in BST
is root
).
Upvotes: 4