访问冲突二叉搜索树模板
Acces Violation binary search tree template
>我对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>
中,您可以创建名为 tempL
和 tempR
的两棵树。在操作员身体的尽头,这些树木被摧毁。这些树的析构函数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 来避免这些类型的头痛。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 正在尝试重载二进制搜索树分配运算符
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- 使用C++创建特殊的二叉搜索树
- C++尝试深度复制唯一指针时出现内存访问冲突
- 在递归二叉搜索树中搜索
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 访问冲突二叉搜索树模板
- 二叉搜索树 - 访问冲突
- 0xC0000005中0x770115de处未处理的异常:使用递归矢量搜索读取位置0xccccccc0时发生访问冲突
- 提升属性树访问冲突
- 删除二叉搜索树中的节点中的 Visual Studio 中的访问冲突异常
- 添加节点时C++二叉搜索树状态访问冲突错误
- 访问二叉搜索树中的违规读取位置0x00000000
- 递归函数插入二叉搜索树无法按根访问节点
- 内存访问冲突插入结构在树结构c++
- 在函数中访问二叉搜索树