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

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;
			}
		}
};

你可能感兴趣的:(引用计数型指针的的简单实现)