自己实现简单的智能指针

#include<string>
#include<iostream>
using namespace std;
template<class T>
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()
{
share<A>sp(new(std::nothrow) A());
sp->n = 10;

share<A>sp2 = 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<A>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<string>
#include<iostream>
using namespace std;
template<class T>
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源码,应该用:<span style="color: rgb(36, 39, 41); font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 15px; line-height: 19.5px;">boost::detail::atomic_count</span>
};

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

};

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


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值