为什么此C 代码不会从堆中删除对象
Why is this C++ code not deleting an object from the heap?
我正在学习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或[...]派生的类型的对象,则需要此转换的程序具有未定义的行为。<<<<<<<<<<
访问对象的成员需要此转换。
相关文章:
- 迭代时从向量和内存中删除对象
- C++从对象自己的类中删除对象
- 如何通过对象的类属性删除对象,并返回其对象值?
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 从列表C++中删除对象
- c++ 循环访问对象列表并删除对象
- 从对象本身的容器中删除对象
- 从尝试引用已删除函数的矢量 C++ 中删除对象
- 如何通过指向元组的共享指针删除对象
- 防止通过接口删除对象
- 在 c++ 中从内存中删除对象
- 当对象被删除时,复制被删除对象的对象如何
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 从内存中删除对象
- 通过C++中的删除方法自行删除对象
- C++ - 析构函数只是释放内存还是实际删除对象
- 如何通过存储在 std::list 中的指针删除对象?
- 如何通过对象参数从指针矢量中删除对象和指针
- 我可以删除对象的右值版本的函数吗?
- 使用对象的索引从矢量中删除对象