二叉树析构函数c++

Binary tree destructor c++

我是 c++ 的新手,我正在做一些练习以更好地学习它。但是,我不明白给定任务的建议解决方案的析构函数中发生了什么。我试图在网上寻找解释,但还没有找到..

这是练习中给出的二叉树:

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);
}

练习是为此 class 创建一个析构函数。在我在网上找到的所有其他二叉树示例中,析构函数都是以某种方式递归实现的。但是,解决方案手册建议这样做:

Tree::~Tree() {
delete _left;
delete _right;
}

这将如何运作?在我看来,这个析构函数只会删除一个节点的左右指针?或者这个析构函数是否也以某种方式递归?

delete-ing左右节点调用它们的析构函数。所以递归释放所有资源。

cppreference告诉

If expression is not a null pointer [...] the delete expression invokes the destructor

或来自当前草稿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.

当您在指针上调用 delete 运算符时,将调用该对象的析构函数。因此,在您的情况下,调用将沿着二叉树传播。

除此之外,我想指出您的代码被认为是 旧 C++。我知道你还在学习,这只是一个练习。但理想情况下,您应该使用 std::unique_ptrstd::shared_ptr 等智能指针来管理指针所有权。这些 类 简化了代码,因为当您不再需要它们时,它们会自动销毁指向的对象(例如,您的对象被销毁并且没有其他对象指向这些对象)。当您使用这些类型的指针时,您必须了解一些规则(例如,循环依赖可能是一个问题),但它们确实值得学习和使用。

我可以给你的另一个提示是停止使用 NULL 并开始使用 nullptr

如果您想了解有关这些问题的更多信息,可以阅读 Scott Meyers 的一本名为 Effective Modern C++ 的书,其中解释了这些要点以及更多内容。