1. 程式人生 > >智慧指標類的實現

智慧指標類的實現

#include <iostream>
using namespace std;
template <typename T>
class SmartPointer{
public:
	SmartPointer(T *p=0):poin(p),use(new size_t(1)){}
	SmartPointer(const SmartPointer &p){
		if(this!=&p)
		{
			poin = p.poin;
			use  = p.use;
			++(*use);
		}
	}
	SmartPointer& operator=(const SmartPointer &tmp)
	{
		if(poin==tmp.poin)
			return *this;
		++*tmp.use;
		if(--*use==0)
		{
			cout<<"解構函式被呼叫了"<<endl;
			delete poin;
			delete use;
		}
		poin = tmp.poin;
		use  = tmp.use;
		return *this;
	}
	T& operator*()
	{
		cout<<"get in"<<endl;
		return *poin;
	}

	~SmartPointer()
	{
		if(--(*use)==0)
		{
			cout<<"解構函式呼叫"<<endl;
			delete poin;
			delete use;
		}
	}
    void Print()
	{
		cout<<*use<<"    "<<*poin<<endl;
	}
private:
	T *poin;
	size_t *use;
};
int main()
{
	SmartPointer<int> a(new int(4));
	a.Print();
	SmartPointer<int> c;
	c=a;
	cout<<"a........."<<endl;
	a.Print();
	cout<<"c........."<<endl;
	c.Print();
	return 0;
}