智能指针(引用计数版)

#include<iostream>

using namespace std;

template<class T> class smartPoiter;

template<class T>
class u_ptr
{
private:
	int num;
	T *ptr;    

	u_ptr(T* p): num(1),ptr(p) {cout << "创建" << endl;}
    ~u_ptr()
	{
		delete ptr;
	}
 
	friend class smartPoiter<T>;
};


template<class T>
class smartPoiter
{
private:
	u_ptr<T>* poiter;

public:
	smartPoiter(T* p = 0):poiter(new u_ptr<T>(p)) {}
    smartPoiter(smartPoiter& rhs): poiter(rhs.poiter)
	{
		++(poiter->num);
		cout << "拷贝构造 还有" << poiter->num << endl;
	}
 
	smartPoiter& operator=(const smartPoiter& rhs);
    
	T* operator->() const       //const表明不能修改主调对象 
	{
		return(poiter->ptr);
	}
	
	T& operator*() const
	{
		return(*(poiter->ptr));
	}

	~smartPoiter()
	{
		if(--(poiter->num) == 0)
		{
			delete poiter;
			cout << "全部删除" << endl;
		}
		else
		{
		    cout << "还有" << poiter->num << "个智能指针" << endl;
		}
	}
};

//rhs的应用次数加1,主调对象减1 
template<class T>
smartPoiter<T>& 
smartPoiter<T>::operator=(const smartPoiter<T>& rhs)   
{
    ++(rhs.poiter->num);       //这种写法还是可以
    
	if(--(poiter->num) == 0)
	{
        delete poiter;
	}

	poiter = rhs.poiter;
	return(*this);
}

struct point
{
	int x,y;
	point(int a,int b): x(a),y(b) {}
};

int main()
{
	smartPoiter<point> p(new point(5,6));
    cout << p->x << " "  << p->y << endl;
    smartPoiter<point> p1 = p;
 	cout << p1->x << " "  << p1->y << endl;
//	p = p;    //测试自我复制 
	cout << p->x << " "  << p->y << endl;
	cout << (*p).x << " " << (*p).y << endl; 

	return(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值