#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() {
AutoPtr<int > t(new int(1));
}
1. auto_ptr重载了操作符&,*和->。不要被语法误导,记住pstr是一个对象,不是一个指针。只是它重载了这些操作符后, 使用上相指针一样.
2. 不要将auto_ptr对象作为STL容器的元素。C++标准明确禁止这样做,否则可能会碰到不可预见的结果
3. 不要将数组作为auto_ptr的参数, 可以理解到在auto_ptr中, 使用delete, 但没有使用delete [].
4. auto_ptr不能作为容器的成员。
5. 不能通过赋值操作来初始化auto_ptr
std::auto_ptr<int> p(new int(42)); // OK
std::auto_ptr<int> p = new int(42); // ERROR
这是因为auto_ptr 的构造函数被定义为了explicit