我一直在阅读的C++书中指出,当使用delete
操作符删除指针时,指向它的位置的内存被"释放"并且可以被覆盖.它还指出指针将继续指向同一位置,直到重新分配或设置为NULL
.
但是在Visual Studio 2012中; 这似乎不是这样的!
例:
#include <iostream>
using namespace std;
int main()
{
int* ptr = new int;
cout << "ptr = " << ptr << endl;
delete ptr;
cout << "ptr = " << ptr << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译并运行该程序时,我得到以下输出:
ptr = 0050BC10
ptr = 00008123
Press any key to continue....
Run Code Online (Sandbox Code Playgroud)
显然,当调用delete时,指针指向的地址会发生变化!
为什么会这样?这是否与Visual Studio有关?
如果删除可以改变它指向的地址,为什么不删除自动设置指针NULL
而不是一些随机地址?
c++ pointers memory-management delete-operator visual-studio-2012
我写了一个简单的,工作的俄罗斯方块游戏,每个块作为类单块的一个实例.
class SingleBlock
{
public:
SingleBlock(int, int);
~SingleBlock();
int x;
int y;
SingleBlock *next;
};
class MultiBlock
{
public:
MultiBlock(int, int);
SingleBlock *c, *d, *e, *f;
};
SingleBlock::SingleBlock(int a, int b)
{
x = a;
y = b;
}
SingleBlock::~SingleBlock()
{
x = 222;
}
MultiBlock::MultiBlock(int a, int b)
{
c = new SingleBlock (a,b);
d = c->next = new SingleBlock (a+10,b);
e = d->next = new SingleBlock (a+20,b);
f = e->next = new SingleBlock (a+30,b);
}
Run Code Online (Sandbox Code Playgroud)
我有一个扫描完整行的函数,并运行删除相关的块的链接列表并重新分配 - >下一个指针. …