Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.
(1)delete operator works only for objects allocated using operator new (See http://geeksforgeeks.org/?p=8539).
If the object is created using new, then we can do delete this, otherwise behavior is undefined.
1 class A 2 { 3 public: 4 void fun() 5 { 6 delete this; 7 } 8 }; 9 10 int main() 11 { 12 /* Following is Valid */ 13 A *ptr = new A; 14 ptr->fun(); 15 ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr. 16 17 18 /* And following is Invalid: Undefined Behavior */ 19 A a; 20 a.fun(); 21 22 getchar(); 23 return 0; 24 }
(2)Once delete this is done, any member of the deleted object should not be accessed after deletion.
1 #include<iostream> 2 using namespace std; 3 4 class A 5 { 6 int x; 7 public: 8 A() 9 { 10 x = 0; 11 } 12 void fun() 13 { 14 delete this; 15 16 /* Invalid: Undefined Behavior */ 17 cout << x; 18 } 19 }; 20 int main() 21 { 22 A *a = new A; 23 a->fun(); 24 25 return 0; 26 }
Output: 一个随机数
The best thing is to not do delete this at all.
Thanks to Shekhu for providing above details.
References:
https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this
http://en.wikipedia.org/wiki/This_%28computer_science%29
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 09:42:47