标签:
#pragma once #include<iostream> #include<string> using namespace std; template<typename T> class SmartPointer { //不允许有SmartPointer sp=new T()这样的使用方式能给sp赋值的只有另一个sp对象和构造方法 public: SmartPointer(T* p = 0) :ptr(p), ref_count(new size_t)//构造函数 { if (ptr) *ref_count = 1; } SmartPointer(SmartPointer& src)//拷贝构造函数 { if (this != &src) { ptr = src.ptr; ref_count = src.ref_count; (*ref_count)++; } } T& operator*()//操作符重载,注意返回类型 { if (ptr) return *ptr; //throw exception; } T* operator->()//操作符重载,注意返回类型 { if (ptr) return ptr; //throw exception; } SmartPointer& operator=(SmartPointer& src)//操作符重载,注意返回类型 { if (this == &src) return *this; releaseCount(); ptr = src.ptr; ref_count = src.ref_count; (*ref_count)++; return *this; } int getRefCount(){ return *ref_count; }//返回计数值 ~SmartPointer(){ releaseCount(); }//析构函数 private: T* ptr; size_t* ref_count; void releaseCount()//计数减一,若减一后为0,释放内存 { if (ptr && --(*ref_count) == 0) { delete ptr; delete ref_count; } } }; void main() { SmartPointer<string> cp1(new string("a")); cout << *cp1 << endl; cout << cp1->size() << endl; SmartPointer<string> cp2(cp1); cout << *cp1 << endl; cout << cp1->size() << endl; cout << cp1.getRefCount() << endl; SmartPointer<string> cp3; cp3 = cp2; cp3 = cp1; cp3 = cp3; cout << cp3.getRefCount() << endl; SmartPointer<string> cp4(new string("b")); cp3 = cp4; cout << cp1.getRefCount() << endl; system("pause"); }
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/45245087