考虑下面的代码:了解删除C运营商++
#include <iostream>
#include <string>
using namespace std;
class A{
public:
int x;
public:
A(){x=0;}
void fun1(){
cout << "fun1 is called \n";
cout << "Address of this is " << this <<endl;
delete this;
}
void fun2()
{
cout << "fun2 called \n";
}
~A()
{
cout << "Object Destroyed" << endl;
}
};
int main()
{
A* ptr=new A;
cout << "Address of ptr is " << ptr <<endl;
ptr->fun1();
ptr->fun2();
return(0);
}
输出为:
$ ./TestCPP
Address of ptr is 0x20010318
fun1 is called
Address of this is 0x20010318
Object Destroyed
fun2 called
我的问题是,当我们在fun1()
称之为delete
它破坏由this
指针即在所指向的对象地址0x20010318
。它通过输出显示调用析构函数。因此,在调用fun1()
后,地址0x20010318
处的对象被销毁并释放内存。那么为什么在输出中我们可以看到fun2()
?它只是垃圾价值?我的意思是该对象不存在,但在ptr -> fun2()
所指的位置fun2()
的定义仍然存在?
也可以有人请解释delete
如何工作。比如打电话new
来电operator new
和constructor
,是delete
操作类似?
感谢
查看http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 –
更有趣:'int main(){ {tmp; } something_else(); }' - 假设由于缺乏副作用,内部块没有得到优化,无论如何.... – twalberg