参考:
- 《STL源码剖析》
- C++智能指针及其简单实现
1. autpptr简易实现
template<class T>
class AutoPtr
{
public:
AutoPtr(T *p = nullptr) :pointer(p){}
~AutoPtr(){ delete pointer; }
AutoPtr(AutoPtr<T> &rhs) : pointer(rhs.release()){
}
AutoPtr<T>& operator=(AutoPtr<T>& rhs){
if (&rhs != this){
reset(rhs.release());
}
return *this;
}
T* get(){ return pointer; }
T& operator*()const{ return *pointer; }
T* operator->()const{ return pointer; }
private:
T* release(){
T *result = pointer;
pointer = nullptr;
return result;
}
void reset(T *p){
delete pointer;
pointer = nullptr;
pointer = p;
}
private:
T *pointer;
};
测试
int main()
{
AutoPtr<int> ap(new int);
*ap = 5;
cout << *(ap.get()) << endl;
AutoPtr<int> ap2(new int);
*ap2 = 25;
cout << *(ap2.get()) << endl;
ap = ap2;
cout << *(ap.get()) << endl;
return 0;
}