C++分析研究  
C++
日历
<2014年3月>
2324252627281
2345678
9101112131415
16171819202122
23242526272829
303112345
统计
  • 随笔 - 92
  • 文章 - 4
  • 评论 - 4
  • 引用 - 0

导航

常用链接

留言簿

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

  一、智能指针
  在C++语言编程时,当类中有指针成员时,一般有两种方式来管理指针成员:一是采用值型的方式管理,每个类对象都保留一份指针指向的对象的拷贝;另一种更优雅的方式是使用智能指针,从而实现指针指向的对象的共享。
  智能指针(smartpointer)的一种通用实现技术是使用引用计数(referencecount)。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。
  每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,析构函数减少引用计数(如果引用计数减至0,则删除基础对象)。
  智能指针详解:
  包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost::intrusive_ptr
  二、智能指针的一般实现  www.jamo123.com
  智能指针通常使用类模板来实现。模拟类指针的各种行为。但是,其最重要的作用是对类指针成员的管理,防止悬垂指针的出现。
  template<classT>
  classSmartPointer{
  public:
  SmartPointer(T*t):pt(t){}
  T&operator*(){return*pt;}
  T*operator->(){returnpt;}
  private:
  T*pt;
  };
  三、引用计数的实现
  为了实现引用计数,我们定义一个_counter类来记录引用次数,把_counter类的所有成员设定为private,因为其他的类型并不需要访问_counter,只有SmartPointer对其进行操作就行了,SmartPointer将设为其友元类。
  class_counter{
  template<classT>friendclassSmartPointer;
  _counter(intu):use(u){}
  ~_counter(){}
  intuse;
  };
  在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对象,
实现 www.lefeng123.com
  _counter的use成员(引用计数)为2.
  四、测试
  intmain(void)
  {
  HasPtr*php=newHasPtr(3);
  SmartPointer<HasPtr>psp(php);
  SmartPointer<HasPtr>npsp(psp);
  SmartPointer<HasPtr>nnpsp=npsp;
  return0;
  }

posted on 2014-03-18 17:13 HAOSOLA 阅读(251) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


 
Copyright © HAOSOLA Powered by: 博客园 模板提供:沪江博客
PK10开奖 PK10开奖