Reputation:
I am pretty new to c++ and I am doing some exercises to learn it better. However, I do not understand what is going on in the destructor of the proposed solution of a given task. I have tried to look online for an explanation, but not found one yet..
This is the binary tree given in the exercise:
class Tree {
Tree *_left;
Tree *_right;
string _name;
public:
Tree(string name) : _left(NULL), _right(NULL), _name(name) {}
void insert(string name);
void insert(const Tree &tree);
friend ostream& operator<<(ostream&, const Tree&);
};
void Tree::insert(string name) {
Tree **destination = &_right;
if (name < _name) {
destination = &_left;
}
if (*destination == NULL)
(*destination) = new Tree(name);
else
(*destination)->insert(name);
}
The exercise is to make a destructor for this class. In every other example of binary trees I have found online, the destructor is implemented recursively in some way. However the solution manual suggests this:
Tree::~Tree() {
delete _left;
delete _right;
}
How will this work? To me it looks like this destructor will only delete the left and right pointer of one node? Or is this destructor also in some way recursive?
Upvotes: 2
Views: 1553
Reputation: 4884
When you call the delete
operator on a pointer, the destructor of that object will be called. So, in your case, the call will propagate down the binary tree.
Besides that, I would like to point out that your code is considered old C++. I understand you are still learning and this is only an exercise. But ideally, you should be using smart pointers like std::unique_ptr
or std::shared_ptr
to manage pointer ownership. Those classes simplify the code because they destroy the pointed objects automatically when you don't need them anymore (e.g., your object is destroyed and no other object points to those objects). There are some rules you have to understand when you work with those types of pointers (e.g., circular dependency could be a problem), but they are really worth learning and using.
Another tip I can give you is to stop using NULL
and start using nullptr
.
If you want to learn more about these issues, there is a book called Effective Modern C++ by Scott Meyers that explains those points and much more.
Upvotes: 2
Reputation: 280
delete
-ing the left and right node calls their destructors. So all the resources are freed recursively.
cppreference tells
If expression is not a null pointer [...] the delete expression invokes the destructor
Or from the current draft expr.delete#6
If the value of the operand of the delete-expression is not a null pointer value and the selected deallocation function (see below) is not a destroying operator delete, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.
Upvotes: 3