C++ 为什么这样做有效?删除后为指针指定新的int值

C++ 为什么这样做有效?删除后为指针指定新的int值,c++,pointers,c++11,memory,dynamic,C++,Pointers,C++11,Memory,Dynamic,我有以下代码: #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; d

我有以下代码:

#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;
}
为什么这样做有效?为什么我仍然可以使用指针?发生了什么事


这在某种程度上有用吗?

这是典型的未定义行为,而且它恰好工作,因为先前分配给
*ptr
的内存尚未被操作系统回收*。您永远不应该依赖这种代码

注意指针的地址保持不变,因为C++运行时不费力地去取消指针(它需要时间,C++中你不需要支付你不需要的东西)。


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

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

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;
int*ptr=newint(15);

cout虽然使用了delete关键字,但由于某些原因,指针没有被取消分配。(可能指针的作用域仍在使用)


指针是C++的一个重要方面,使用指针处理引用级别或内存地址很重要。“工作”并不意味着你认为它能做什么。它看起来像是工作代码。。。但事实并非如此。尝试为其他资源“malloc”一些新内存,您的代码将覆盖从其他资源分配的内存。简单地说:您的代码是“未定义的行为”。一切都可能发生,从“看起来像在工作”到崩溃。只需在

*ptr=30之前分配更多内存删除
内存,则假定您再也无法访问它。
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;