我刚刚编写了一个示例程序,以查看删除此
的行为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
问题
m使用linux ubuntu和g ++编译器
答案 0 :(得分:9)
Eric Lippert在his answer中提供了一个非常漂亮的“酒店房间的桌子抽屉里的书”,在函数返回后提出了一个关于局部变量指针的问题,它同样适用于此处。
答案 1 :(得分:2)
让我们将其与类似的szenario进行比较:
A *a= new A();
func(a);
delete a;
func2(a);
在我的示例中,编译器只是将指针a传递给func和func2,它不关心它是否指向有效对象。因此,如果您调用func2(a)
并且func2取消引用指针,则这是未定义的行为。如果内存被释放回操作系统并且程序无法访问* a,程序可能会崩溃。通常删除会保留已分配的内存,不会将其传递回操作系统,因此在删除后访问* a不会产生异常,只返回任何值。这可能是* a的先前值,但也可能是任何其他值,具体取决于删除的实现,并取决于delete a
和*a
之间对新完成的其他调用。例如,MSVC在调试模式下将内存设置为预定义模式,以便您在访问释放的内存时可以轻松识别。
为什么这与你的问题有关?因为编译器将this
作为隐藏的隐式参数传递。