C ++ Depth Exploration Series: Smart Pointer2

zhaozj2021-02-16  75

Deep exploration intelligent pointer (SmartPointer)

Subject index:

I. Analyze C Standard Library Intelligent Pointer (std :: auto_ptr) 1.Doyousmartpointer? 2.std :: auto_ptr Design Principle 3.std :: Auto_PTR Advanced User Guide 4. Do you feel std :: auto_ptr is not perfect enough?

Second, C conditions, find a strategy for constructing more powerful smart pointers 1. Support multiple design strategies for reference records 2. Support for multiple resources 3. Support SubClassing4. Support for multi-thread conditions, thread security Design strategy 5. Other special requirements, then construct

Third, GenericProgramming Basic Technology and SmartPointer1. Looking back in TRAITS technology in resources 2. Back to multithreaded support

Fourth, COM implementation, smartpointer design principle

5. Status of SmartPointer in the famous C library (standard and non-standard)

-------------------------------------------------- -------------------

Second, C conditions, find a strategy for constructing more powerful smart pointers 1. Support a variety of design strategies to reference a number of design strategies, have you heard of COM and its famous IUNKNOWN interface? What is iUnknown? I want to tell you In the three function signatures of the iunknown interface, two are used to manage objects (CoClassObject, component class objects) to control its life cycle. In practice, our object is not only once, only one is allowed Quote.

So, who is to manage its life cycle? Our strategy is: Reference record. When the reference number of the object is zero, it is destroyed. In fact, the destruction of the target is often AUTO_PTR. In COM, destroying objects is object yourself. In fact, it and our smart pointer is not a level of concept. Our smart pointer is responsible for the object level reference. And COM is based on interface reference as core To ensure the interface operation, the interface references are automatically managed. Oh! Yes! So how do we give auto_PTR plus object reference modes?

Strategy 1: An object corresponds to a reference count object. The smart pointer is a proxy with a count object. Imagine, this is also returned to the classic "adding intermediate layer" solution. # Core 1: We add a "reference) . class "it has two functions: a reference count maintained .b object pointer as the object of maintenance schematic structure: templateclassObjRefCounted {private: T * m_OBJ_Delegate_Ptr; unsignedintm_UIcounted; public:... explicitObjRefCounted (T * m_Paramin = 0): m_UIcounted (1), m_OBJ_Delegate_Ptr (m_Paramin) {}; templateObjRefCounted (ObjRefCounted & x) {m_OBJ_Delegate_Ptr = x.m_OBJ_Delegate_Ptr);}; ObjRefCounted (constObjRefCounted & x): m_UIcounted (x.m_UIcounted), m_OBJ_Delegate_Ptr (x.m_ObjDelegate_Ptr) {}; ~ ObjRefCounted ( ); voidreleaseref (); voidaddref (); t * getRealpointer () const;}; ..}; Through the above two strategies, we can pay a reference count object when the smart pointer is constructed. This object is responsible for hosting the SmartPointer's object pointer that should be maintained. And responsible for finally eliminating the object.

In SmartPointer, we will involve a large number of _m_objrefcounted operations. Next, a process, in detail, design it in detail. For example, when you assign an object to smartpointer to build an auxiliary reference to the hosted object At this time, m_uicounted is 1, m_obj_delegate_ptr is assigned a target pointer, if I now give SmartPointer to another SmartPointer2, then smartpointer2 call _m_objrefcounted-> ReleaseRef (); reduce the number of objects for maintenance, put their own _ M_objrefCounted is set to SmartPointer2, then call _m_objrefcounted-> addref (); ok! That's. Policy 2. Maintain an object pointer and a pointer to a reference value in each smart pointer. Here The focus is to maintain a pointer to a reference value, which makes a consistent ratio between SmartPointer to be possible. Structure is as follows: TemplateClassSmartPointer {private: t * m_objptr; unsignedint * refcounted; public: explicitsmartpoint (t * paramin = 0): m_ObjPtr (PARAMin), RefCounted (newint (1)) {} SmartPoint (constSmartPoint & PARAMin2): m_ObjPtr (PARAMin2.m_ObjPtr), RefCounted (PARAMin2.RefCounted) { * RefCounted;} .......}; but this The scalability of the method is poor. Because the reference count function is combined to the SmartPointer. Generally does not use this method. Based on the two strategies, according to the actual situation, more record methods can be designed. 2. Using Traits (PartialSpecialization) technology, support to handle multiple resources in NO1, we mentioned not to let Auto_PTR management arrays, because the AUTO_PTR parsing function is called DELETE. Array is not, other, such as file Handle, thread handle, etc. Of course, it is even more

Below we will discuss this problem:

Policy 1. With a function pointer to support the processing of multiple resources. Our smart pointer will be designed with a template class with two parameters. The first parameter indication: the second parameter of the resource is indicated: the function type structure of the resource Drawing is as follows:

typedefvoidFreeResourceFunction (void * p); voidDealSingleObject (void * p); voidDealArray (void * p); voidDealFile (void * p); //// added function pointer // templateclassSmartPointer {public declarations for special resource: ~ SmartPointer () {DEALFUNCTION ();} ... / * OtherCodes * /};

Inlinevoiddealsingle (void * p) {if (p) deletep;}

Inlinevoiddealarray (Void * P) {if (p) delete [] p;} inlinevoiddealfile (void * p) {if (p) p-> close ();} /// The process of adding processing functions for special resources /////

OK! But when we use this strategy, we must pay attention to that the passing pointer cannot be wrong. Of course, it is also necessary to retrofit the above structure, so that it has stronger identification bad ability. .

3. Support Subclassing Subclassing about smart pointers, let's look at what is a program fragment: classBaseClass {}; classDerived:? PublicBaseClass {}; auto_ptrm_Derived; auto_ptrm_Base; auto_ptrpDerived = newDerived; m_Base = pDerived; //// m_Derived = (PderiveD &) M_Base; // # 1 // See the top # 1 No, you think in auto_ptr, it or the same semantic behavior can be performed? Can't. Why? It essentially, quite right: baseclass * m_baseclass; m_baseclass = newderivedclass (INPARAM); this is obviously illegal. Only we have, Auto_Ptr on the type with virtual characteristics, can also reflect virtuality.

However, it does not access the inherited data, and it is not true Subclassing.

Then we do this to achieve such functions. Policy 1. In the SMATPoint described in the above reference count, we do the following: TemplatesmartPointer & Operator = (constsmartpointer & That) {if (m_prep! = Reinterpret_cast (That.m_prep )) {ReleaseRef (); m_prep = reinterpret_cast (That.m_prep); addref ();} return * this;}};

Good, reinterpret_cast, it is to help us solve problems.

Strategy 2. About the second method, this is no longer detailed. It involves too many details, the peak back is difficult to say. Generally, it is a target pointer maintained in the reference count object to void * and in specific The call is converted via static_cast or reinterpret_cast. In short, the so-called subclassing technique is inseparable from transformation.

4. Support for multi-threading conditions, multiple design strategies for thread safety are not very concerned for standard C . The reason is that the standard library does not support multithreading. Policy 1: First of all, we think: Access synchronization. So we have two options: a. Building a critical area object. Pass the execution of the object to the critical area. To ensure security .b. Use the temporary object to complete the task, and leave the critical responsibility to the role Object. The second approach is analyzed below: Programme1: classwidget {... voidlock (); // Enter the critical area voidunlock (); // Exit critical zone}; Programme2: TemplateClassLockingProxy {public: LockingProxy (t * pobj): Pointee_ (POBJ) {Pointeee_-> Lock ();} // In the temporary object structure, it is locked // weight object (critical area). ~ LockingProxy () {Pointee_-> unlock ();} /// In temporary When the object is destroyed, exit the critical zone .//t*operator ,> ()const@returnpointee_; }////reload -> operator. To perform // request the method of the temporary object // request to Weight object // PRIVATE: LOCKINGPROXY & OPERATOR = (constlockingproxy &); t * pointee_;};

Programme3: TemplateClassSmartptr {... LOCKINGPROXYOPERATOR -> () const {returnckingProxy (Pointee _);} /// The core is here: generating temporary object // LockingProxy (Pointee_) Private: st * pointee_;};

Programmed4.smartptrsp = ...; sp-> DOSMETHING (); // ## 1 Next, we simulate, execute the process. ## 1 When executed, build a temporary object LockingProxy (POINTEE_) This object is in the construct Lock the Weight object and pass the dosomethin () method to the Weight object, execute, the temporary object disappears, the parsing function exits the critical area.

4. Other special requirements, the re-construct a. Back to the year, auto_ptrm_smptr = newx (100) in the year; actually not! NOPROBLEM! Auto_PTR (t * m_paramin = 0) Shrow (): m_tp (m_paramin) { } Solve the problem. B.Considerit: voidfook (x * m_paramin) {}; but I only have auto_ptrm_smptr; NOPROBLEM! T * Operatort * (auto_ptr & m_paramin) throw () {returnm_tp;} fook (m_smptr); // ok! Nowc. Facts You can override more or join the function member function according to your needs.

-------------------------------------------------- ------------to be continued

Third, GenericProgramming Basic Technology and SmartPointer1. Looking back in TRAITS technology in resources 2. Back to multithreaded support

Fourth, COM implementation, smartpointer design principle

5. Status of SmartPointer in the famous C library (standard and non-standard)

-------------------------------------------------- ----------------

-------------------------------------------------- ------------ Solemn statement: Allow copying, modification, delivery, or other behavior but is not allowed for any commercial use. Written 20/3/2003 Last modified: 20/3 / 2003Bytomhorn 4 Hotmail.com ------------------------------------------------------------------------------------------------------------------------ ---------------

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

New Post(0)