在析构函数中访问违反"删除"指针

Bon*_*nev 0 c++ memory exception access-violation c++11

我的二进制搜索树析构函数看起来像这样.

~BSTree()
{
    if (this == nullptr || this->left == nullptr && this->right == nullptr)
    {
        return;
    }
    this->left->~BSTree();
    delete this->left;
    this->right->~BSTree();
    delete this->right;
}
Run Code Online (Sandbox Code Playgroud)

调用堆栈获取有关> = 4后叫我的程序崩溃在if()访问Voilation例外.

我的领域是只有三个:int key;,BSTree *left;BSTree *right;

在此输入图像描述

它似乎this不是NULL但它的字段无法从内存中读取.如何检查是否可以,remove this;如果不能防止异常?

Chn*_*sos 7

多件事:

  1. 除非与新的展示位置一起使用,否则不要自己调用析构函数.

  2. 按C++标准,this不能等于nullptr.如果是,你有更严重的问题.

  3. delete 已经自动调用析构函数.

  4. delete可以nullptr毫无问题地通过.

你的析构函数应该如下所示:

~BSTree()
{
    delete left;
    delete right;
    // possibly ...
    left = right = nullptr;
}
Run Code Online (Sandbox Code Playgroud)