#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;
}
}