C ++ depth exploration series: Smart Pointer [2]

zhaozj2021-02-16  42

Deep exploration intelligent pointer (Smart Pointer)

Subject index:

First, analyze C standard library smart pointer (std :: auto_ptr) 1.Do you smart pointer? 2.std :: auto_ptr Design principle 3.std :: auto_ptr Advanced User Guide 4. Do you think std :: auto_ptr is not enough? perfect?

Second, C conditions, find a strategy for constructing more powerful smart pointers 1. Support for a number of design strategies for reference score 2. Support to process multiple resources 3. Support SubClassing 4. Support for multithreading conditions, thread security A variety of design strategies 5. Other special requirements, re-construct

Third, Generic Programming Basic Technology and Smart Pointer 1. Looking back to Traits Technology in Resources 2. Looking back over multithreaded support

Fourth, COM implementation, Smart Pointer design principle

V. Status of Smart Pointer 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 (Coclass Object, component class objects) to control its life cycle. In practice, our object is not only once, only allowed A referenced.

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) "It". Its duty has two: a. Maintenance of the reference number of the object. b. Maintain the object's pointer. Structure is as follows: Template class objrefCounted {private: t * m_obj_dlegate_ptr; unsigned int m_uicount; public: explicit ObjRefCounted (T * m_Paramin = 0): m_UIcounted (1), m_OBJ_Delegate_Ptr (m_Paramin) {}; template ObjRefCounted (ObjRefCounted & x) {m_OBJ_Delegate_Ptr = x.m_OBJ_Delegate_Ptr);}; ObjRefCounted (const ObjRefCounted & x : m_uicounted (x.m_uicounted), m_obj_dlegate_ptr (x.m_objdelegate_ptr) {}; ~ ObjrefCounted (); void releaseref (); void addRef (); t * getRealPointer () const;}; # core 2 In smart pointer maintenance A reference to the pointer Template Class SmartPointer {public: objrefcounted * _m_objrefcounted; ..... .....}; Through the above two strategies, we can pay a reference count object when it is constructed in the smart pointer. This object is responsible The hosted Smart Pointer should have a target pointer that should be maintained. And responsible for finally eliminating the object.

In Smart Pointer, we will involve a large number of _m_objrefCounted operations. The following is a process, in detail, designed. For example, when you assign an object to Smart Pointer to build an auxiliary reference Hosting object, at this time, m_uicounted is 1, m_obj_delegate_ptr is assigned to object pointer, if I now give Smart Pointer to another SmartPointer2, then smartpointer2 call _m_objrefcounted-> releaseref (); reduce the number of objects for maintenance, will Your 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 here is to maintain a pointer to a reference value, which makes the uniform count value between the Smart Pointer becomes possible. Structure is as follows: Template Class SmartPointer {Private: T * m_objptr; unsigned int * refcount; public: explicit SmartPoint (T * PARAMin = 0): m_ObjPtr (PARAMin), RefCounted (new int (1)) {} SmartPoint (const SmartPoint & PARAMin2): m_ObjPtr (PARAMin2.m_ObjPtr), RefCounted (PARAMin2.RefCoun TED) { * refcounted;} .... ...}; but this method is poorly spread. Because the reference count function is combined into the Smart Pointer. Generally do not use this method. The two strategies are based. According to the actual situation, more modified methods can be designed. 2. Use Traits (Partial Specialization technology to support processing multiple resources in NO1, we mentioned non-AUTO_PTR management array, then It is because the Auto_Ptr paratory function is called DELETE. An array is not, such as a file handle, a 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:

Typedef void freeeresourcefunction (void * p); void deaRray (void * p); void dealfile (void * p); // // Declaration of a function pointer to special resource Declaration // Template Class SmartPointer {public: ~ smartpointer () {deaalFunction ();} ... / * other code * /}; inline void dealsingle (void * p) {if (p) delete P;

Inline void dealarray (void * p) {if (p) delete [] p;} inline void dealfile (void * p) {if (p) p-> close ();} // Add to handle 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 in the smart pointer, what is it? Let's first look at the one-rule fragment: class baseclass {}; class derived: public baseclass {}; auto_ptr m_derived; auto_ptr m_base; auto_ptr pderived = new derived; m_base = pderived; // // m_derived = (pderived &) m_base; // # 1 //

Seeing the # 1 above, you think in auto_ptr, can it be executed in Auto_PTR? No. Why? It is essentially, quite with this: baseclass * m_baseclass; m_baseclass = new derivedClass (Inparam); This is obviously illegal. Only we used the AUTO_PTR to a class with virtual characteristics, but also virtuality.

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

Then, we will implement such a function. Policy 1. In the SmartPoint described in the above reference count, we make the following operations: Template smartpointer & operator = (Const SmartPointer & 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. Create a critical area object. Pass the execution of the object to the critical area. To ensure security. B. Use temporary object to complete the task, and leave the critical responsibility to be used Object. The following analysis: Programme1: Class Widget {... void Lock (); // Enter the critical area void unlock (); // Exit critical area}; Programme2: Template Class LockingProxy { Public: LockingProxy (T * pobj): Pointee_ (POBJ) {Pointee_-> Lock ();} // In the temporary object constructor, it is locked // weight object (critical area). ~ LockingProxy () {Pointee _-> unlock );} // // When the temporary object is destroyed, the critical area is exited. // t * operator -> () const {return pointee_;} // // Here, the Operator. Method of Temporary objects Execute // Request to transfer to Weight object // private: Lockingpr Oxy & operator = (const LockingProxy &); T * Pointee_;}; Programme3: Template class smartptr {... lockingProxy operator -> () const {returnPockingProxy (Pointee_);} // // The core is here: generating temporary objects // LockingProxy (Pointee_) private: st * pointee_;};

Programmme4. Smartptr sp = ...; sp-> dosomething (); // ## 1

Below, we simulate, execute the process. ## 1 Execute, build a temporary object LockingProxy (Pointee_) This object is locked in the constructor, and the DOSMETHIN () method is passed to the Weight object, in After the method is executed, the temporary object disappears, the termination function exits the critical region. 4. Other special requirements, re-constructing a. Looking back, you don't feel auto_ptr m_smptr = new x (100); actually nothing. Not cool. ! No problem! Auto_PTR (T * m_paramin = 0) Shrow (): m_tp (m_paramin) {} solve the problem. B. consider it: void fook (x * m_paramin) {}; but I only have auto_ptr m_smptr; no Problem! T * Operator T * (Auto_Ptr & m_Paramin) throw () {return m_tp;} fook (m_smptr); // ok! now c. In fact, you can use your own needs. Reversions More or Join the function member function.

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

Third, Generic Programming Basic Technology and Smart Pointer 1. Looking back to Traits Technology in Resources 2. Looking back over multithreaded support

Fourth, COM implementation, Smart Pointer design principle

V. Status of Smart Pointer in the famous C library (standard and non-standard)

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

-------------------------------------------------- ------------ Solemn statement: Allow copy, modification, delivery or other behavior but is not allowed for any commercial use. Writing 20/3/2003 Last modified: 20/3/2003 by redstar81 81_redstar@163.com--------------------------------------------- ----------------

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

New Post(0)