基类Uc_object 如下:
class Uc_object { private: unsigned int count_d; public: Uc_object():count_d(0){} Uc_object(const Uc_object&):count_d(0){} virtual ~Uc_object(){} void increment(){++count_d;} void decrement() { if (--count_d==0) { delete this; } } unsigned int use_count() { return count_d; } };
模板类Uc_ptr如下:
template <class T> class Uc_ptr { private: T* ptr; public: Uc_ptr(T* =0); Uc_ptr(const Uc_ptr<T>& ); ~Uc_ptr(); const Uc_ptr<T>& operator=(const Uc_ptr<T>&); operator T*()const {return ptr;} T* operator->()const {return ptr;} };
模板类Uc_ptr的实现如下:
template <class T> Uc_ptr<T>::Uc_ptr(T* arg):ptr(arg) { if(ptr) ptr->increment(); } template <class T> Uc_ptr<T>::Uc_ptr(const Uc_ptr<T>& arg):ptr(arg.ptr) { if (ptr) { ptr->decrement(); } } template<class T> Uc_ptr<T>::~Uc_ptr() { if (ptr) { ptr->decrement(); } }template<class T> const Uc_ptr<T>& Uc_ptr<T>::operator=(const Uc_ptr<T>& arg) {
if(ptr) { ptr->decrement(); } if (ptr=arg.ptr) { ptr->increment(); } return *this;
}
使用Uc_ptr来实现rep 类
class String_rep:public Uc_object { friend class String; char* data; String_rep(const char* cp); ~String_rep(); };
rep的实现如下:
String_rep::String_rep(const char* cp):data(new char[strlen(cp)+1]) { strcpy(data,cp); } String_rep::~String_rep() { delete []data; }
String 类的实现如下:
class String { private: Uc_ptr<String_rep> rep; public: String(const char* cp=""):rep(new String_rep(cp)) { } void printStr() { printf("%s",rep->data); } };
我们可以随便写个测试代码来测试这个使用了计数器的智能指针模板
int _tmain(int argc, _TCHAR* argv[]) { String a=String("heping"); a.printStr(); return 0; }