在SmartPointer类中,保留_counter的指针。
template<classT> classSmartPointer{ public: SmartPointer(T*t):pc(new_counter(1)){ cout<<"SmartPointer::SmartPointer()invodeduseis:"<<pc->use<<endl; this->pt=t; } SmartPointer(SmartPointer<T>&rhs){ this->pc=rhs.pc; this->pt=rhs.pt; this->pc->use++; cout<<"SmartPointercopyinvokeduseis:"<<pc->use<<endl; } ~SmartPointer(){ pc->use--; cout<<"SmartPointer::~SmartPointer()invodeduseis:"<<pc->use<<endl; if(pc->use==0) { deletept; deletepc; } } SmartPointer<T>&operator=(SmartPointer<T>rhs){ if(rhs==*this){ return*this; } this->pt=rhs.pt; this->pc=rhs.pc; this->pc->use++; cout<<"SmartPointer::operator=()invokeduseis:"<<pc->use<<endl; return*this; } private: T*pt; _counter*pc; }; |
例如:我们有一个HasPtr类,其类成员中有一个为指针*p。
classHasPtr{ public: HasPtr(intval):value(val),p(newint(3)){ cout<<"HasPtr::HasPtr()invoked"<<endl; } ~HasPtr(){deletep;cout<<"HasPtr::~HasPtr()invoded"<<endl;} private: int*p; intvalue; }; |
如果如下调用:
HasPtr*php=newHasPtr(3);
SmartPointer<HasPtr>psp(php);
SmartPointer<HasPtr>npsp(psp);
我们现在有两个智能指针对象,指向同一个HasPtr对象,其模型如下:
_counter的use成员(引用计数)为2.