#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;
这是我为展示我所说的内容所做的改进描述:
关于c++ - 这种删除指针的行为正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860298/