// vc下的智慧指標,重點在於擁有權的轉移
#include <iostream>
using namespace std;
template<class Type>
class Autoptr
{
public:
Autoptr(int *p = NULL) :ptr(p), owns(ptr != NULL)
{}
Autoptr(const Autoptr<Type> &t) :ptr(t.release()), owns(t.owns)
{}
Autoptr<Type>& operator=(const Autoptr<Type> &t)
{
if (this != &t)// 判斷是否給自己賦值
{
if (ptr != t.ptr)// 判斷是否指向同一個空間
{
if (owns)// 如果有擁有權,則釋放當前空間
{
delete ptr;
}
else
{
owns = t.owns;// 反之,得到擁有權
}
ptr = t.release();// 讓t失去擁有權
}
}
return *this;
}
~Autoptr()
{
if (owns)
delete ptr;
}
public:
Type& operator*()const
{
return (*get());
}
Type* operator->()const
{
return get();
}
Type* get()const
{
return ptr;
}
Type* release()const
{
((Autoptr<Type> *const)this)->owns = false;
return ptr;
}
private:
bool owns;
Type *ptr;
};
int main()
{
int *p = new int(10);
Autoptr<int> pa(p);
cout << *pa << endl;
Autoptr<int> pa1(pa);
cout << *pa1 << endl;
int *p1 = new int(100);
Autoptr<int> pa2(p1);
Autoptr<int> pa3;
pa3 = pa2;
cout << *pa3 << endl;
return 0;
}