shared_ptr 实现

自己实现了一个菜得抠脚的shared_ptr ,

自己存草稿看看吧

template<class T>
struct Type{
	typedef T type;

};
class SPCountBase{
	public :
		int used_count_;
		void AddOne(){
			used_count_++;
			cout<<"add "<< used_count_<<endl;
		}
		void DecreaseOne(){
			used_count_--;
			cout<<"decreate "<< used_count_<<endl;
		}
		void Destory(){
			delete this;
		}
		int used_count(){
			return used_count_;
		}
		SPCountBase() :used_count_(1){}
		virtual ~SPCountBase() { }


};
template <class T>
class CountImpl : public SPCountBase{
	typedef CountImpl<T> this_type;
	public : 
		T * px_;
		CountImpl(T * p):  px_(p) {
			cout<<" CountImpl() "<<endl;   
		}
		~CountImpl() {  
			cout << "~CountImpl()" <<endl; 
				delete px_;}

};
class SharedCount{ //为什么要抽象出这个count来
	public:
		SPCountBase * pi_;	

		template <class T> 
		SharedCount( T *p){
			pi_ = new CountImpl<T>(p);
		}
		SharedCount( ) : pi_(){
		}
		~SharedCount(){
			if(pi_){
				pi_->DecreaseOne();
				if(pi_->used_count() == 0){
					delete pi_;	
				}
			}	
		}

};
template <class T>
class MyShared {
	public :
		T * px_; //保存的是原始指针的内容
		SharedCount  pn_;//处理引用计数问题
		MyShared (){
		
		
		}
		template <class X>
		MyShared ( X *p) : px_(p) , pn_(p) {

		
		}
		MyShared &operator = (MyShared <T> const &r){
			px_ = r.px_;
			pn_.pi_ = r.pn_->pi_;
			dynamic_cast< CountImpl<T> *> (pn_.pi_)->px_ = 
				dynamic_cast< CountImpl<T> *>(r.pn_->pi_)->px_;
			pn_.pi_->AddOne();
			return *this;
		}
		MyShared (MyShared <T> const &r){
			px_ = r.px_;
			pn_.pi_ = r.pn_.pi_;
			dynamic_cast< CountImpl<T> *> (pn_.pi_)->px_ = 
				dynamic_cast< CountImpl<T> *>(r.pn_.pi_)->px_;
			pn_.pi_->AddOne();
		}

};
class Test{
	public :
		Test(){
			cout<<"Test()"<<endl;
		}
		~Test(){
			cout<<"~Test()"<<endl;
		}

};
int main()
{
	Test *s = new Test();
	MyShared <Test>  ss0(s);
	MyShared <Test>  ss1(ss0);
	MyShared <Test>  ss2(ss0);

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值