1 class Counted { 2 private: 3 unsigned int count_; 4 public: 5 Counted() : 6 count_(0) { 7 } 8 virtual ~Counted() { 9 } 10 Counted *retain() { 11 count_++; 12 return this; 13 } 14 void release() { 15 count_--; 16 if (count_ == 0) { 17 count_ = 0xDEADF001; 18 delete this; 19 } 20 } 21 22 23 /* return the current count for denugging purposes or similar */ 24 int count() const { 25 return count_; 26 } 27 };
使用的例子
1 /* counting reference to reference-counted objects */ 2 template<typename T> class Ref { 3 private: 4 public: 5 T *object_; 6 explicit Ref(T *o = 0) : 7 object_(0) { 8 reset(o); 9 } 10 Ref(const Ref &other) : 11 object_(0) { 12 reset(other.object_); 13 } 14 15 template<class Y> 16 Ref(const Ref<Y> &other) : 17 object_(0) { 18 reset(other.object_); 19 } 20 21 ~Ref() { 22 if (object_) { 23 object_->release(); 24 } 25 } 26 27 void reset(T *o) { 28 if (o) { 29 o->retain(); 30 } 31 if (object_ != 0) { 32 object_->release(); 33 } 34 object_ = o; 35 } 36 Ref& operator=(const Ref &other) { 37 reset(other.object_); 38 return *this; 39 } 40 template<class Y> 41 Ref& operator=(const Ref<Y> &other) { 42 reset(other.object_); 43 return *this; 44 } 45 Ref& operator=(T* o) { 46 reset(o); 47 return *this; 48 } 49 template<class Y> 50 Ref& operator=(Y* o) { 51 reset(o); 52 return *this; 53 } 54 55 T& operator*() { 56 return *object_; 57 } 58 T* operator->() const { 59 return object_; 60 } 61 operator T*() const { 62 return object_; 63 } 64 65 bool operator==(const T* that) { 66 return object_ == that; 67 } 68 bool operator==(const Ref &other) const { 69 return object_ == other.object_ || *object_ == *(other.object_); 70 } 71 template<class Y> 72 bool operator==(const Ref<Y> &other) const { 73 return object_ == other.object_ || *object_ == *(other.object_); 74 } 75 76 bool operator!=(const T* that) { 77 return !(*this == that); 78 } 79 80 bool empty() const { 81 return object_ == 0; 82 } 83 };
指针导入引用,就会被自动释放