访问冲突二叉搜索树模板

Acces Violation binary search tree template

本文关键字:搜索树 访问冲突      更新时间:2023-10-16

>我对C++很新,我最近收到了一个使用模板创建自己的二叉搜索树的项目。目标是让二叉树能够接受任何类型的数据类型。我创建了 2 个类,Node(h,cpp),Tree(h,cpp) 和一个主 cpp。出于某种原因,我一直得到访问违规(可能来自析构函数,它正在获取损坏的值)。

。这是我的代码(这是整个事情,所以它更容易..).谢谢。。。

template <typename T>
std::ostream& operator<<(std::ostream& output, const Tree<T>& tree)
{
    if (!tree.getRoot())
        return output;
    Node<T> * temp=tree.getRoot();
    Tree<T>  tempL(temp->getL());
    output<<tempL;
    output<<temp->getValue();
    output<<endl;

    Tree<T> tempR(temp->getR());
    output<<tempR;

    return output;
}
#endif
#include "Tree.h"
void main ()
{
    Node<int> *no=new Node<int>(7);
    Tree<int> IntTree(no);
    IntTree.insert(new Node<int> (5));
    IntTree.insert(new Node<int> (0));
    IntTree.insert(new Node<int> (4));
    IntTree.insert(new Node<int> (5));
    IntTree.insert(new Node<int> (12));
    IntTree.insert(new Node<int> (7));
    IntTree.insert(new Node<int> (1));
    IntTree.insert(new Node<int> (14));
    IntTree.insert(new Node<int> (7));
    IntTree.insert(new Node<int> (51));
        if(IntTree.exists(5.1))
        cout<<IntTree;
}

看起来问题是节点被删除了两次。在 operator<< for Tree<T> 中,您可以创建名为 tempLtempR 的两棵树。在操作员身体的尽头,这些树木被摧毁。这些树的析构函数delete提供给它们的节点。但是,这些节点不是他们的要销毁的,因为它们也属于提供给operator<<的树对象。在运算符调用结束时,流式传输的任何树对象现在都指向已删除的节点。我已经注释了操作员的身体来说明我的意思:

template <typename T>
std::ostream& operator<<(std::ostream& output, const Tree<T>& tree)
{
    if (!tree.getRoot())
        return output;
    Node<T> * temp=tree.getRoot();  // temp->getRoot() wil be deleted temp is destroyed
                                    // this will also destroy temp->getL() and temp->getR()
                                    // because of Node<T>'s destructor
    Tree<T>  tempL(temp->getL());   // will delete temp->getL() when tempL is destroyed
    output<<tempL;
    output<<temp->getValue();
    output<<endl;

    Tree<T> tempR(temp->getR());    // will delete temp->getL() when tempR is destroyed
    output<<tempR;

    // tempL and tempR are destroyed
    return output;
}

要解决此问题,您应该避免在operator<<中制作临时树。此外,考虑使用智能指针,如 std::shared_ptr 和 std::unique_ptr 来避免这些类型的头痛。