主要在于引用计数的使用
代码示例:
templateclass Ptr{ template friend class Ptr;protected: vint* counter; T* reference; void Inc() { if(counter) { (*counter)++; } } void Dec() { if(counter) { if(--(*counter)==0) { delete counter; delete reference; counter=0; reference=0; } } } vint* Counter()const { return counter; } Ptr(vint* _counter, T* _reference) :counter(_counter) ,reference(_reference) { Inc(); }public: Ptr() { counter=0; reference=0; } Ptr(T* pointer) { if(pointer) { counter=new vint(1); reference=pointer; } else { counter=0; reference=0; } } Ptr(const Ptr & pointer) { counter=pointer.counter; reference=pointer.reference; Inc(); } template Ptr(const Ptr & pointer) { T* converted=pointer.Obj(); if(converted) { counter=pointer.Counter(); reference=converted; Inc(); } else { counter=0; reference=0; } } ~Ptr() { Dec(); } template Ptr Cast()const { C* converted=dynamic_cast (reference); return Ptr ((converted?counter:0), converted); } Ptr & operator=(T* pointer) { Dec(); if(pointer) { counter=new vint(1); reference=pointer; } else { counter=0; reference=0; } return *this; } Ptr & operator=(const Ptr & pointer) { if(this!=&pointer) { Dec(); counter=pointer.counter; reference=pointer.reference; Inc(); } return *this; } template Ptr & operator=(const Ptr & pointer) { T* converted=pointer.Obj(); Dec(); if(converted) { counter=pointer.Counter(); reference=converted; Inc(); } else { counter=0; reference=0; } return *this; } bool operator==(const T* pointer)const { return reference==pointer; } bool operator!=(const T* pointer)const { return reference!=pointer; } bool operator>(const T* pointer)const { return reference>pointer; } bool operator>=(const T* pointer)const { return reference>=pointer; } bool operator<(const T* pointer)const { return reference & pointer)const { return reference==pointer.reference; } bool operator!=(const Ptr & pointer)const { return reference!=pointer.reference; } bool operator>(const Ptr & pointer)const { return reference>pointer.reference; } bool operator>=(const Ptr & pointer)const { return reference>=pointer.reference; } bool operator<(const Ptr & pointer)const { return reference & pointer)const { return reference<=pointer.reference; } operator bool()const { return reference!=0; } T* Obj()const { return reference; } T* operator->()const { return reference; }};
1