考虑下面的代码:
#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
我的问题是,当我们调用它时delete,fun1()它会破坏this指针指向的对象,即地址0x20010318。它调用析构函数,如输出所示。因此,fun1()在地址处调用对象后被0x20010318销毁并释放内存。那么为什么在输出中我们可以看到fun2()呢?它只是垃圾值吗?我的意思是该对象不存在但在ptr -> fun2()定义所指向的位置fun2()仍然存在?
也有人可以解释一下是如何delete工作的。比如调用newcallsoperator new和constructor,delete操作类似吗?
谢谢