c++ - 为什么这段 C++ 代码没有从堆中删除对象?

标签 c++

<分区>

我正在学习 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。

最佳答案

在对象被销毁后访问它是未定义的行为。你的程序可以做任何事情。碰巧你仍然得到值 3

4.1/1 [conv.lval] A glvalue of a non-function, non-array type T can be converted to a prvalue. [...] If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or [...], a program that necessitates this conversion has undefined behavior.

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

关于c++ - 为什么这段 C++ 代码没有从堆中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205044/

相关文章:

c++ - 访问全局数组比作为参数传递更有效?

c++ - 如何获取 OpenCV getGaussianKernel 返回的 Mat 的实际核值?

c++ - 使用已被 std::move 到别处的变量时出现错误,或至少出现警告

C++ - std::map.insert() 段错误

c++ - 如何在 C++ 代码中显示托管 C# 代码的异常消息

c++ - "new std::complex"和 "fftw_malloc"哪个更安全、高效?

c++ - 将派生类构造函数分配给基类指针

c++ - 在 Cygwin 中处理 "C compiler cannot create executables"

c++ - 参数包上的广义 lambda 捕获?

java - 如何使用 for 语句获取数组或数组列表中的所有 n 组三个连续元素?