我刚刚写了一个示例程序来查看删除这个的行为
class A
{
~A() {cout << "In destructor \n ";}
public:
int a;
A() {cout << "In constructor \n ";}
void fun()
{
cout << "In fun \n";
delete this;
cout << this->a << "\n"; // output is 0
this->fun_2(); // how m able to call fun_2, if delete this is called first ??
}
void fun_2()
{
cout << "In fun_2 \n";
}
main()
{
A *ptr = new A;
ptr->a = 100;
ptr->fun(); //delete this will be executed here
ptr->fun_2(); //how m able to execute fun_2 when this pointer is deleted ??
cout<< ptr->a << "\n"; //prints 0
return 0;
}
> Output
In constructor
In fun
In destructor
0
In fun 2
In fun 2
0
问题
- 在 fun() 中执行delete this后,如何使用 fun() 中的指针访问 func_2() ?
- 现在主要是如何在删除该指针时执行obj->fun_2 ?
- 如果我能够在杀死这个对象后访问函数成员,那么为什么数据成员的值为零'0'?
m 使用 linux ubuntu 和 g++ 编译器