在成员函数中使用'delete this'后,我可以访问其他成员函数。为什么?

时间:2012-08-09 16:17:34

标签: c++ linux oop this-pointer

我刚刚编写了一个示例程序,以查看删除此

的行为
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

问题

  1. 在fun()中执行删除此后,如何在fun()中使用此指针访问func_2()?
  2. 现在主要是我能够做 obj-&gt; fun_2 这个指针被删除了吗?
  3. 如果我在杀死此对象后能够访问函数成员,那么为什么数据成员将为零“0”?
  4. m使用linux ubuntu和g ++编译器

2 个答案:

答案 0 :(得分:9)

  1. 您看到的是未定义的行为:它可能有效,或者可能会崩溃。
  2. 指针指向已删除的实例 - 它是一个悬空指针。
  3. 这也是一种未定义的行为:您可能会看到零或垃圾值。
  4. Eric Lipperthis 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作为隐藏的隐式参数传递。