为什么这行得通?删除后将新的 int 值分配给指针

Why does this work? Assigning a new int value to a pointer after delete

我有这个代码:

#include <iostream>

using namespace std;

void main(){
    int *ptr = new int(15);

    cout << "Address of ptr: " << ptr << endl;
    cout << "Content of ptr: " << *ptr << endl << endl;

    delete ptr;
    *ptr = 30;

    cout << "Address of ptr: " << ptr << endl;
    cout << "Content of ptr: " << *ptr << endl;
}

这是输出:

Address of ptr: 007B81F0
Content of ptr: 15

Address of ptr: 007B81F0
Content of ptr: 30

为什么这行得通?为什么我仍然可以使用指针?发生什么事了?

这在某些时候有用吗?

这是典型的未定义行为,它恰好起作用,因为之前分配给 *ptr 的内存尚未被操作系统回收*。你不应该依赖这种代码。

请注意,指针的地址保持不变,因为 C++ 运行时不会费心使指针无效(这需要时间,而且在 C++ 中,您不需要为不需要的东西付费)。

*另请参阅下面 Remy Lebeau 的评论。

正如 vsoftco 所解释的那样,OS 尚未回收内存。现在,如果我们执行如下操作,您可能会体验到完全不同的输出:

int *ptr = new int(15);

cout << "Address of ptr: " << ptr << endl;
cout << "Content of ptr: " << *ptr << endl << endl;
delete ptr;

int *ptr2 = new int(15); // making a new ptr to use memory.
*ptr = 30;               // <- OPS!
delete ptr2;             // deleting new ptr.

cout << "Address of ptr: " << ptr << endl;
cout << "Content of ptr: " << *ptr << endl;

无论如何,结果是未定义的行为

虽然使用了 delete 关键字,但由于某种原因没有发生指针的取消分配。(可能指针的范围仍在使用中)

使用指针是C++的一个重要方面。使用指针处理引用级别或内存地址很重要。