#include <iostream>
#include <stack>
#include <stdio.h>
using namespace std;
template <class T>
class AutoPtr{
private:
T *m_ptr;
public:
explicit AutoPtr(T *p=0): m_ptr(p){}
AutoPtr (AutoPtr &a):m_ptr(a.release()){}//拷贝构造函数,将原值拷贝,并设为0
AutoPtr &operator = (AutoPtr &a) {
if(this == &a)
return *this;
delete m_ptr;
m_ptr = a.release();
return *this;
}
~AutoPtr() {
delete m_ptr;
}
T& operator *(){
return *m_ptr;
}
T* operator ->() {
return m_ptr;
}
T *get() {
return m_ptr;
}
T* release() {//返回指针,并自己设为0
T *tmp = m_ptr;
m_ptr = 0;
return tmp;
}
void reset(T *p = 0) {
if (p != m_ptr) {
delete m_ptr;
m_ptr = p;
}
}
};
int main
auto_ptr的简单实现
最新推荐文章于 2020-05-23 14:17:56 发布