DELETE THIS, DLL Export Class and How to Write Plugins (Part I)

zhaozj2021-02-08  215

1. Why use delete this, and how to use it. (1) Check out this: There are two objects A, B need to access the same polymorphism 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 more ugly implementation method), so it cannot be delete in the middle of A / B, and a fold is to come to Delete when the program exits, but this will not release the resource release If there is a plurality of 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.

转载请注明原文地址:https://www.9cbs.com/read-1954.html

New Post(0)