c++ - 对于 C++ 中的指针,delete 命令真正对内存有什么作用?

标签 c++ memory-management new-operator

Possible Duplicate:
C++ delete - It deletes my objects but I can still access the data?
Can a local variable's memory be accessed outside its scope?

当我想释放用 new 分配的内存时,我不明白 delete 究竟做了什么。在 C++ Premiere 书中写道:

This removes the memory to which ps pointer points; it doesn’t remove the pointer ps itself. You can reuse ps, for example, to point to another new allocation. You should always balance a use of new with a use of delete; otherwise, you can wind up with a memory leak—that is, memory that has been allocated but can no longer be used. If a memory leak grows too large, it can bring a program seeking more memory to a halt.

所以据我了解 delete 必须删除内存中 pinter 指向的值。但事实并非如此。这是我的实验:

int * ipt = new int;   // create new pointer-to-int

cout << ipt << endl;   // 0x200102a0, so pointer ipt points to address 0x200102a0
cout << *ipt << endl;  // 0, so the value at that address for now is 0. Ok, nothing was assigned
*ipt = 1000;     // assign a value to that memory address
cout << *pt << endl;   // read the new value, it is 1000, ok
cout << *((int *) 0x200102a0) << endl;   // read exactly from the address, 1000 too

delete ipt;   // now I do delete and then check
cout << ipt << endl;  // 0x200102a0, so still points to 0x200102a0
cout << *ipt << endl;  // 1000, the value there is the same
cout << *((int *) 0x200102a0) << endl;    // 1000, also 1000 is the value

那么 delete 究竟做了什么?

最佳答案

将内存想象成一个大仓库,里面有很多盒子可以放东西。当您调用"new"时,仓库工作人员会找到一个足够大的未使用的盒子以满足您的需求,将该盒子记录为您拥有(因此它不会给其他人),并给您该盒子的编号以便您可以放置你的东西放进去。这个数字就是“指针”。

现在,当您“删除”该指针时,会发生相反的情况:仓库工作人员注意到该特定框再次可用。与真正的仓库工作人员相反,他们没有对盒子做任何事情——所以如果你在“删除”后查看它,你可能会看到你的旧东西。或者你可能会看到其他人的东西,如果盒子在此期间被重新分配。

从技术上讲,一旦您将箱子放回游泳池,您就不能再查看箱子了,但这是一个有点奇怪的仓库,没有 key 或 guard ,所以您仍然可以为所欲为。但是,它可能会导致盒子的新主人出现问题,因此希望您遵守规则。

关于c++ - 对于 C++ 中的指针,delete 命令真正对内存有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11603005/

相关文章:

database - 全新的应用程序如何向下兼容客户旧的本地数据库?

C: 使用 realloc 的内存错误

c++ - 使用了可能未初始化的本地指针变量 'node'。 C++

c# - C# EmguCV Image.setValue(...) 方法的 C++ OpenCV 等价物

c++ - 找到最高和最低的数字

r - R 可以保存函数创建的对象以供将来使用吗?

objective-c - 自定义 NSObject 类,实例化为 [CustomObj customObjWithData :data]

android - 是否可以在 android 的同一个选项卡中打开新的 Intent ?

c++ - delete[] 的这种行为是否符合预期 - 仅删除前两个元素?

c++ - MFC 和 Windows API 在获取屏幕分辨率方面的区别