c++ - 这种删除指针的行为正常吗?

标签 c++ pointers

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <cmath>

using namespace std;

template <class T>
class binary_node {
public:
    T data;
    binary_node<T> *left;
    binary_node<T> *right;

    binary_node(const T& data)
        :data(data), left(NULL), right(NULL) {
    }
};

int main() {
    binary_node<int>* node = new binary_node<int>(10);
    node->left = new binary_node<int>(1);
    node->right = new binary_node<int>(50);

    binary_node<int>* ptr = node->left;

    delete ptr;
    ptr = NULL;

    if (node->left == NULL) {
        cout << "????";
    }
    else {
        cout << node->left->data << endl;
    }   

    return 0;
}

我希望 node->left == NULL,但结果完全出乎意料,即使 node->left 的数据是垃圾。我使用的是 Visual C++ 2010,谁能帮我解释一下这种行为?

编辑
另一方面,当像这样逐个节点遍历和删除节点时,它工作得很好:

    ~linkedlist() {
#if DEBUG
        cout << "~linkedlist() called.\n";
#endif
        while (head != NULL) {
#if DEBUG
            cout << "delete node: " << head->data << '\n';
#endif
            node<T>* temp = head;
            head = head->next;
            delete temp;
            temp = NULL;
        }
    }

最佳答案

您正在删除分配给 node->left 的数据对象即。 new binary_node<int>(50)对象。

但是您正在通过另一个指针进行删除。然后你将另一个指针设为 NULL

node->left 永远不会设置为空。因此,无论它指向什么(释放内存)的内容就是它所指向的内容。

试试这个:

binary_node<int>** ptr = &(node->left); 

delete *ptr; 
*ptr = NULL; 

或者这个

delete node->left; 
node->left = NULL; 

这是我为展示我所说的内容所做的改进描述: enter image description here

关于c++ - 这种删除指针的行为正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860298/

相关文章:

c - 带有指针变量的地址数组

c - 排列矩阵?

c++ - 如何用我的代码编译两个相似的头文件,以便在其上运行 2 个 DLL

c++ - 如何在 C++ 中获取预加载的模块名称

c++ - 在 C++ 接口(interface)中使用 Boost.Range

c - 二进制搜索指针动态内存分配递归

c - 了解 c 中的内存分配和指针

c++ - 如果编译时大小未知,如何动态分配固定字符数组?

c# - 在 C++ 与 C# 中通过引用传递

c - 在C中添加到链表的尾部