之前转载了一篇文章:<<auto_ptr详解>>
地址:http://blog.youkuaiyun.com/shawvichan/article/details/16959475
为了帮助理解其工作原理,此处自己写类模板来简单地模拟auto_ptr智能指针。
#include <iostream>
using namespace std;
template <typename T>
class autoptr{
T* p;
public:
autoptr(T* p=0):p(p){}
~autoptr(){delete p;}
autoptr(autoptr& a):p(0){operator=(a);}
//autoptr(autoptr& a){operator=(a);}//错误的拷贝构造函数,p没有初始化,将是野指针,会delete出错
autoptr& operator=(autoptr& a){
if(this==&a) return *this;
/*如果之前管理的内存不为空,释放之前管理的内存*/
if(p!=NULL) {
//cout << "free previous memory\n";
delete p;
}
p = a.p;
a.p = NULL;
return *this;
}
/* *和->重载 */
T& operator*()const{return *p;}
T* operator->()const{return p;}
};
class A{
int data;
public:
A(int d):data(d){cout<<this<<"A("<<d<<")"<<endl;}
~A(){cout<<this<<"~A()"<<data<<endl;}
void show()const{cout<<this<<":"<<data<<endl;}
};
int main()
{
autoptr<A> p(new A(10));
p->show();
autoptr<A> q(p);
//p->show();出错,p已经没有动态内存的所有权了
q->show();
autoptr<A> r(new A(20));
(*r).show();
r = q;
r->show();
(*r).show();
autoptr<A> x;
x=r;
(*x).show();
}
/*输出:
0x8567008A(10)
0x8567008:10
0x8567008:10
0x8567018A(20)
0x8567018:20
free previous memory
0x8567018~A()20
0x8567008:10
0x8567008:10
0x8567008:10
0x8567008~A()10
*/