This is a code of reference counting pointers. The goal is a lightweight, high efficiency implementation, avoiding the frequent NEW / Delete reference count of frequently implemented NEW.
Some explanations:
Q: Why is the Delete object in Ref_Count Release, not the external ref_count_ptr to release the object?
A: Put the destruction of the object to a relatively high level, so that the programmer is easier to control the destruction strategy of the object, which looks very tempting. However, the problem is that when we use ref_count_ptr, it means that we need to pass this object. This process may span different modules. The storage management between different modules may be completely different. If it is mixed, it will lead to unpredictable behavior.
Q: why not provide coordination?
A: Considering the feature of Assembler, after the parent class and subclasses are assembled, the bare pointer of Assembler <> has lost the ability to convert mutual conversion, so there is no significance of providing coordination here.
#ifndef refcount_h # defract.h "Namespace nice {// NAMESPACE NICE {// Typically, it should be combined as a policy to the object, not the base class of the inherited tree //, therefore, Virtual public inherits is often necessary. struct Non_ref_count {}; Class Ref_count // The combined object will be released through Delete, so the assignment of the object must be able to meet this requirement. // This can result in a problem when you use the Allocator policy. // 2. You can not use the Stack object // 3. Not as an array member, it is not an array, but it can be a container {public: // Publishing Interface ref_count (): count_ (0) {} Virtual ~ ref_count ) {} // default ctor && assignment int Add_ref () {return count_;}; int release () {int TMP = --count_; if (tmp == 0) delete this; returnit;} public: / / queries int count () const {return count_;} private: int count_;}
Template
REF_COUNT_PTR (const ref_count_ptr & rhs): obj_ (rhs.obj_) {INC ();
Ref_count_ptr & operator = (const ref_count_ptr & rhs) {refrence (rhs.obj_); return * this;}
INS_TYPE * REFRENCE () Const {Return Obj_;}
Void Refrence (IF (Obj == Obj_) return;
Release ();
Obj_ = Obj; Inc ();} INS_TYPE * OPERATOR -> () const {pre_condition (! is_null (), "derefrence null pointer"); returnobj_;} INS_TYPE & OPERATOR * () const {pre_condition (! is_null (), "derefrence Null pointer"); return * obj_;} bool is_null () const {return obj_ == 0;} #define MEMBER_OPE (ope) / inline bool operator ope (const ref_count_ptr & rhs) const / {/ return obj_ ope rhs. Obj _; /} Member_ope (==) Member_ope (! =) MEMBER_OPE () Member_ope (<=) Member_ope (>) Member_ope (> =) # undef Member_ope Private: Void Release () {Obj_! = 0 && Obj_-> release ();} void inc () {if (obj_ = 0!) obj _-> add_ref ();} ins_type * obj_;}; template
#ENDIF / / END REFCOUNT_H Guard