智能指针的简易实现

 

#include <iostream>
using namespace std;
class smart_count{
private:
	int use_count;
public:
	smart_count(int c=0):use_count(c){
	
	}
	~smart_count(){}
	int addref(){
		return ++use_count;
	}
	int release(){
		return --use_count;
	}
};
template<class T>
class smart_ptr{
private:
	T* p;
	smart_count* u;
public:
	smart_ptr(T* tp):p(tp),u(new smart_count(1)){
	}
	smart_ptr():p(NULL),u(NULL){}
	~smart_ptr(){
		if(p&&u->release()<=0){
			delete p;
			delete u;
			p = NULL;
		}
	}
	smart_ptr(smart_ptr<T>& sp){
		p = sp.p;
		u = sp.u;
		if(u){
			u->addref();
		}
	}
	smart_ptr<T>& operator=(smart_ptr<T>& t){
		if(p&&u->release()<=0){
			delete p;
			delete u;
		}
		p = t.p;
		u = t.u;
		if(u){
			u->addref();
		}
	}
	T* operator->(){//这段代码让我困惑,这样就能调用p的函数了?
		return p;
	} 
	T& operator*(){
		return *p;
	}
	T* get(){
		return p;
	}
	void reset(T* t){
		if(p&&u->release()<=0){
			delete p;
			delete u;
		}
		p = t;
		if(p){
			u = new smart_count(1);
		}else{
			u = NULL;
		}
	
	}
	
};
class Car{
private:
	int data;
public:
	Car(int d):data(d){
		cout<<"constructor car"<<endl;
	}
	~Car(){
		cout<<"destructor car"<<endl;
	}
	void f(int a=0){
		cout<<"ok = "<<a+data<<endl;
	}
};
int main(){
	Car* cp = new Car(1);
	smart_ptr<Car> sp(cp);
	sp->f(2);
	(*sp).f(2);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值