1. Why use delete this, and how to use it.
(1) Check out such a situation:
There are two objects A, B needs to access the same polymorphic object C.
Because C is generally constructed by the New operation, it must be released by itself, but the objects A, B need to use it, and b does not know when it is complete C, and I don't know when B is used to complete C (of course you can use The method of function communication is notified, but it is a relatively ugly implementation method), so you can't come to Delete in A / B,
A compromised method is to delete when the program exits, but do not do this immediately release, if there are multiple A / B / C will have a relatively large run overhead.
The solution is to add a reference count in C and decide when to release yourself:
Below is the code structure c {c () {nref = 1;}; int Addref () {Return nref;} int release () {if (! - nref) {delete this; return 0;} return nref; } protected: Virtual ~ c () // DONOT Allow Delete from outsides {} int nref;}; is to determine when the count is used to release its own resources. Of course, A / B will be required to call AddRef / Release at the appropriate time. Here is a simple implementation. Struct a {a (c * pc) {m_pc = pc; pc-> addref ();} void do_sth () {; // ... use M_PC M_PC-> Release (); m_pv = null;} protected : c * m_pc;} Class B structure and A are similar, do not write the main function: void main () {c * pc = new C; A CLSA (PC); B CLSB (PC); PC- > Release (); // ok pc Was Hold by Both CLSA and CLSB, SO We don't need it.release.pc = null; a.do_sth (); b.do_sth () ;; // shop no memory leak }
Note: Because it is delete this in the class member function, it is not possible to access any member variables and virtual functions after this statement, otherwise it will illegally.
Another use will be described later.