为什么此C 代码不会从堆中删除对象

Why is this C++ code not deleting an object from the heap?

本文关键字:删除 对象 代码 为什么      更新时间:2023-10-16

我正在学习C ,并且我已经编写了一些代码,以获得一些手动创建和删除对象的经验。我不认为我完全理解删除的语义,因为打印语句仍然打印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。

在对象被破坏后访问它是不确定的行为。您的程序可以做任何事情。碰巧您仍然获得值3

4.1/1 [cons.lval] 一个非功能,非阵列t型t的glvalue可以转换为prvalue。[...]如果glvalue引用的对象不是T型的对象,也不是从t或[...]派生的类型的对象,则需要此转换的程序具有未定义的行为。<<<<<<<<<<

访问对象的成员需要此转换。