| |||||||||
| 日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
|---|---|---|---|---|---|---|---|---|---|
| 26 | 27 | 28 | 29 | 30 | 31 | 1 | |||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | |||
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | |||
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | |||
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | |||
| 30 | 1 | 2 | 3 | 4 | 5 | 6 | |||
















#ifndef AUTOPTR
#define AUTOPTR

/**//**
* 智能指針類
*/
template<class T>
class AutoPtr
{
public :
AutoPtr(T* p = 0) : pointee(p)
{} //默認構造函數
template<class U>
AutoPtr(AutoPtr<U>& rhs) : pointee(rhs.release())
{}//復制構造函數

~AutoPtr()
{delete pointee;}
template<class U>
AutoPtr<T>& operator=(AutoPtr<U>& rhs)
{ //賦值函數
if (this != &rhs)
{
reset(rhs.release());
}
return *this;
}

T& operator*() const
{return *pointee;}

T* operator->() const
{return pointee;}

T* get() const
{return pointee;} //獲取dumb pointer

T* release()
{ //釋放dumb pointer 的擁有權,并返回其值
T* oldPointee == pointee;
pointee = 0;
return oldPointee;
}

void reset(T* p=0)
{ //重復置p指針
if (pointee != p)
{
delete pointee;
pointee = p;
}
}
private :
T* pointee;
};
#endif AUTOPTR
#include "AutoPtr.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
AutoPtr<int> p = new int;
*p = 100;
printf("%d\n", *p);
AutoPtr<string> sp = new string;
*sp = "hello world";
printf("%s\n", sp->c_str());
return 0;
}