[英]Memory leak in assignment operator for binary search tree
所以我似乎无法找出为什么我要泄漏 memory,有人可以帮忙吗? 我用operator=:
BinTree& BinTree::operator=(const BinTree &other)
{
if (other.root == NULL)
root = NULL;
else
{
copyHelper(root, other.root);
}
return *this;
}
复制助手:
void BinTree::copyHelper(Node *¤t, const Node *other)
{
if (other == NULL)
current = NULL;
else
{
current = new Node;
current->data = other->data;
copyHelper(current->left, other->left);
copyHelper(current->right, other->right);
}
}
我明白current = new Node;
是发生泄漏的地方,但是如果我尝试delete current;
在那条线之前。
这是我的析构函数:
BinTree::~BinTree()
{
destroyRecursive(root);
}
void BinTree::destroyRecursive(Node *node)
{
if (node)
{
destroyRecursive(node->left);
destroyRecursive(node->right);
delete node;
}
}
由于您使用原始指针,因此您必须手动删除分配的 memory。 当您将current
设置为 NULL 时,您会泄漏NULL
void BinTree::copyHelper(Node *¤t, const Node *other)
{
if (other == NULL)
{
delete current; // w/o this line next
current = NULL; // will cause memory leak (if not managed somewhere else)
}
else
{
current = new Node;
current->data = other->data;
copyHelper(current->left, other->left);
copyHelper(current->right, other->right);
}
}
代码结构不佳。 C++ 为您提供了执行此操作的所有便利,但您很少或根本没有利用它。 需要删除当前树的根,在operator function中,然后copy-construct新的节点; 你需要修复你的析构函数。
递归复制助手应该是节点 class 中的复制构造函数:
Node::Node(const Node &other): left(0), right(0) { this->data = other.data; // This must be a deep copy if (other.left) this->left = new Node(other.left); if (other.right) this->right = new Node(other.right); }
这由BinTree
赋值运算符调用:
BinTree& BinTree::operator=(const BinTree &other) { delete root; this->root = 0; if (other.root) this->root = new Node(other.root); return *this; }
您不需要递归销毁方法。 在BinTree
的析构函数中,你所需要的只是delete root;
,以及Node
的析构函数:
Node::~Node() { delete left; delete right; }
data
的拷贝必须是深拷贝。 例如,如果它是一个 C 字符串,请在Node
的析构函数中使用strdup(),
和free()
它。 如果它是 class,则该 class 必须具有赋值运算符。
事实上,你不需要两节课。 每个节点都是一棵树。 所以你只需要一个BinTree
class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.