Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c++ - After using 'delete this' in a member function I am able to access other member functions. Why?

I just wrote a sample program to see the behaviour of delete this

class A
 {
   ~A() {cout << "In destructor 
 ";}
 public: 
    int a;
    A() {cout << "In constructor 
 ";}

    void fun()
     {
       cout << "In fun 
";
       delete this;
       cout << this->a << "
"; // 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 
";
    }

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 << "
"; //prints 0
 return 0;
}

> Output
In constructor
In fun
In destructor
0
In fun 2
In fun 2
0

Questions

  1. After executing delete this in fun(), how I am able to access func_2() with this pointer in fun() ??
  2. Now in main how I am able to do obj->fun_2 as this pointer is deleted ??
  3. If I am able to access function members after killing this object, then why data members are comming zero '0' ??

m using linux ubuntu and g++ compiler

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. What you see is undefined behavior: it might work, or it may crash.
  2. The pointer is pointing to a deleted instance - it is a dangling pointer.
  3. This is an undefined behavior as well: you may see a zero or a garbage value.

Eric Lippert provided a very nice "book in a table drawer of a hotel room" analogy in his answer to a question about pointers to local variables after the function has returned, it is equally applicable here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...