自己实现简单的智能指针

#include
#include
using namespace std;
template
class share
{
 public:
 share():point(0){}
  share(T* p1)
  {
       point = p1;
  }
  ~share()
  {
    cout << "begin to delete share" << endl;
     if(NULL != point)
     {
      delete point;
      point = NULL;
     }
  }
  share(share& t2)
  {
      point = t2.point;
      t2.point = NULL;
  }
  share& operator =(share& t2)
  {
      point = t2.p2;
      t2.point = NULL;
      return *this;

  }
  T* operator ->()
  {
        return point;
  }
private:
   T* point;
};

class A
{
public:
   A()
   {
        n = 0;
   }
   int n;
   char v[4];

};

int main()
{
sharesp(new(std::nothrow) A());
sp->n = 10;

sharesp2 = sp;
cout << "sp2->n is :" << sp2->n << endl;
return 0;
}

输出如下:

[root@237 code]# ./a.out 
sp2->n is :10
begin to delete share
begin to delete share



总结:
   1、这种模式是资源独占的,当share
sp2 = sp后,不允许sp再用了,因为此时sp->point == NULL。--这种智能指针相当于std::auto_ptr;
有时会有疑问,既然是因为:sp->point == NULL 导致sp不能用,那在 operator =()函数中,不将‘t2.point = NULL;’不就可以了。别忘了,这样在析构时,sp跟sp2的point指向
同一块内存,而sp->point != sp2->point(指针的数值不等,但是却只想同一块内存),所以会重复释放内存。
   2、为了防止sp=sp2后,再用sp2,可以禁止  拷贝构造函数与赋值运算符。这样就相当于boost::scope_ptr了。


二、可以看出上面的智能指针并不好用,所以为了解决智能指针之间既能复制又能让不同的指针对象对同一块内存操作,引出了用引用计数的智能指针
    (就是boost::share_ptr),代码如下:

#include
#include
using namespace std;
template
class share
{
 public:
  share():point(0),pcount = new int(0){}
  share(T* p1)
  {
       point = p1;
	   if (pcount == NULL)
	   {   
		pcount = new int(1);   
	   }	   
  }
  ~share()
  {
    //cout << "begin to delete share" << endl;
     if(--(*pcount) == 0)
     {
      delete point;
	  delete pcount;
	  pcount = NULL;
	  cout << "begin to delete share" << endl;
      point = NULL;
     }
  }
  share(share& t2)
  {
      point = t2.point;
      t2.(*pcount)++;
	  pcount =  t2.pcount;
  }
  share& operator =(share& t2)
  {
	  if (--(*pcount) == 0)
	  {
		 delete point;   
	  }
	  point = t2.point;
      t2.(*pcount)++;
	  pcount =  t2.pcount;
      return *this;
  }
  T* operator ->()
  {
        return point;
  }
private:
   T* point;
   int* pcount; //应用计数一定是要所有的该类对象共用的  //这个引用计数在多线程下是不安全的。参考boost源码,应该用:boost::detail::atomic_count
};

class A
{
public:
   A()
   {
        n = 0;
   }
   int n;
   char v[4];

};

int main()
{
sharesp(new(std::nothrow) A());
sp->n = 10;
cout << "sp->n is :" << sp->n << endl;
sharesp2 = sp;
sp2->n = 20;
cout << "sp->n is :" << sp2->n << endl;
return 0;
}


你可能感兴趣的:(编程语言,linux)