引用计数型指针的的简单实现

template<typename T>
class Smart_ptr
{
	public:
		Smart_ptr(T*p=0):pointer(p),count(new size_t(p==0?0:1))
		{}
		Smart_ptr(const Smart_ptr<T> &rhs):pointer(rhs.pointer),count(rhs.count)
		{
			++ *count;
		}
		~Smart_ptr()
		{
			decr_count();
		}
		Smart_ptr& operator=(const Smart_ptr<T> &rhs)
		{
// 			if(this !=&rhs)
// 			{
// 			++*count;
// 			decr_count();
// 			pointer=rhs.pointer;
// 			count=rhs.count;
// 			}
// 			return *this;

		Smart_ptr<T>(rhs).Swap(*this);//改进之后是异常安全的
               return *this;
		}
	
		size_t Get_refcount()const
		{
			return *count;
		}
       void Swap(Smart_ptr<T>&rhs)
	   {
		  if(pointer==rhs.pointer)
		  {
			  --*count;
		  }
		  std::swap(rhs.pointer,pointer);
		  std::swap(*rhs.count,*count);
	   }
	private:
		T*pointer;
		size_t *count;//用地址保证指向同一个地址空间,数据的统一性
		void decr_count()
		{
			if(--count==0)
			{
				delete pointer;
				delete count;
			}
		}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值