智能指针(指向转移写法)
来源:互联网 发布:latex windows 10 编辑:程序博客网 时间:2024/06/05 01:18
#include<iostream>using namespace std;template<class T>class auto_ptr{public:explicit auto_ptr(T* p = 0):pointee(p) {} //默认参数的构造函数 auto_ptr(auto_ptr<T>& rhs): pointee(rhs.release()) {} ~auto_ptr() { delete pointee; } auto_ptr<T>& operator=(auto_ptr<T>& rhs) { if(this != &rhs) { reset(rhs.release()); } return(*this); } T& operator*() const { return(*pointee); } T* operator->() const { return(pointee); } T* get() const { return(pointee); } T* release() { T* oldPointer = pointee; pointee = 0; return(oldPointer); } void reset(T *p = 0) { if(pointee != p) { delete pointee; pointee = p; } }private:T* pointee;};struct pt{int x,y; pt(int a,int b):x(a),y(b) {}};int main(){ auto_ptr<pt> p(new pt(4,5)); auto_ptr<int> p2(new int);p2 = p;cout << p->x << endl; auto_ptr<pt> p1 = p;cout << p1->x << endl;return(0);}