<分区>
我正在学习 C++,我已经编写了一些代码来获得一些手动创建和删除对象的经验。我不认为我完全理解 delete 的语义,因为 print 语句仍然打印 3 而我认为它不应该。
代码
#include <iostream>
class Test {
public:
int x;
int y;
};
using namespace std;
int main() {
Test t1;
t1.x = 1;
t1.y = 2;
cout << t1.x << endl;
cout << t1.y <<endl;
Test *t2 = new Test();
t2->x = 3; t2->y = 4;
cout << t2->x << endl;
cout << t2->y <<endl;
delete t2;
cout << t2->x << endl;
}
输出
joel-MacBook-Air:src joel$ ./test
1
2
3
4
3
你能解释一下为什么它在最后打印 3 吗?我知道当我删除对象时它不应该打印 3。