C++智能指针的设计和实现

发表于:2014-3-14 09:40

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:WXS_Borealis    来源:51Testing软件测试网采编

分享:
  在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.
32/3<123>
精选软件测试好文,快来阅读吧~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号