C++ 二叉搜索树赋值运算符中的内存泄漏

C++ 二叉搜索树赋值运算符中的内存泄漏,c++,memory,memory-leaks,variable-assignment,assignment-operator,C++,Memory,Memory Leaks,Variable Assignment,Assignment Operator,所以我似乎无法找出我为什么泄露内存,有人能帮忙吗?我用运算符=,实现了一个二进制搜索树: copyHelper: void BinTree::copyHelper(Node *&current, const Node *other) { if (other == NULL) current = NULL; else { current = new Node; current->data = other->

所以我似乎无法找出我为什么泄露内存,有人能帮忙吗?我用运算符=,实现了一个二进制搜索树:

copyHelper:

void BinTree::copyHelper(Node *&current, 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);
    }   
}
我理解当前=新节点;是泄漏发生的地方,但是如果我尝试删除当前文件,我的程序就会崩溃;在那条线之前

这是我的析构函数:

BinTree::~BinTree()
{
    destroyRecursive(root);
}

void BinTree::destroyRecursive(Node *node)
{
    if (node)
    {
        destroyRecursive(node->left);
        destroyRecursive(node->right);
        delete node;
    }
}

由于使用原始指针,因此必须手动删除分配的内存。将current设置为NULL时会泄漏内存


糟糕的代码结构。C++给了你做这件事的所有便利,但你却很少或根本没有利用它。您需要在操作符函数中删除当前树的根,然后复制并构造新节点;你需要修复你的析构函数

递归复制帮助器应该是节点类中的复制构造函数:

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析构函数中所需的只是删除根;,和节点的析构函数:

数据的复制必须是深度复制。例如,如果它是一个C字符串,则使用strdup,并在节点的析构函数中释放它。如果是类,则该类必须具有赋值运算符


那么节点析构函数是什么样子的呢?注意:你也需要深度复制数据,不清楚是否发生了这种情况。你没有显示一个删除,所以任何人应该如何评论潜在的泄漏?@EJP I补充道destructor@EJP好的,但是我仍然在泄漏memoryNode对于这个练习来说必须是一个结构,从那里我能做什么?没有任何区别,它仍然可以有操作符、构造函数和析构函数。奇怪的要求,请做一个。从张贴的代码中找不到原因。
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::operator=(const BinTree &other)
{
    delete root;
    this->root = 0;
    if (other.root)
        this->root = new Node(other.root);
    return *this;
}
Node::~Node()
{
    delete left;
    delete right;
}