auto_ptr的简单实现
#include<iostream>
using namespace std;
/*
智能指针 boos库里的智能指针
c++11以前ato_ptr
后 unique_ptr shared_ptr weak_ptr
*/
//auto_ptr智能指针的实现
template<typename T>
class Smart_ptr
{
public:
Smart_ptr(T*ptr)
{
}
Smart_ptr(const Smart_ptr<T>& rhs):mptr(rhs.mptr)//拷贝构造函数
{
rhs.release();//rhs是一个常对象
}
Smart_ptr<T>& operator=(const Smart_ptr<T>&rhs)
{
if(this!=&rhs)//自赋值判断
{
delete mptr;
mptr=rhs.mptr;
rhs.release();
}
return *this;
}
~Smart_ptr()
{
delete mptr;
mptr=NULL;
}
//实现对象解引用 重载函数
T& operator*()//*单目运算符 里面有this指针做唯一操作数
{
return *mptr;
}
//->指向运算符的重载 单目运算符
T *operator->()
{
return mptr;
}
private:
void release()const//改变旧智能指针的指向rhs是常对象
{
((Smart_ptr<T>*)this)->mptr=NULL;//强转
}
T* mptr;
};
/*
int *p=new int; *p=20;
class Test
{
public:
void Show();
}
Test* ptest =new Test();
ptest->Show(); 指针不仅要解引用 还要能调用函数 智能指针要把它当做一个指针 所以要有解引用 和指向操作 ----》运算符重载
*/
class Test
{
public:
void Show()
{
cout<<"Test::Show()"<<endl;
}
};
//auto_ptr被摒弃的原因 管理权是唯一的 释放权也唯一
int main()
{
Smart_ptr<int>sp1(new int);
Smart_ptr<int>sp2(sp1);
*sp1=20;//访问保留区
}
/*
int main()
{
Smart_ptr<int>sp1(new int);
//Smart_ptr<int>sp2(sp1);//发生浅拷贝 sp1 拷贝sp2
Smart_ptr<int>sp2(sp1);
Smart_ptr<int>sp3(new int);
sp3=sp2;//赋值运算符的重载函数,指向同一块地址,要实现这个该函数
*sp3=20;
Smart_ptr<Test>sp4(new Test());
sp4->Show; //sp4.operator->() ----->Test* ---->Show()
return 0;
}
*/
//void func(int *ptr)
//{
// auto_ptr<int>p(new int);
// //int *p=new int;
// if(ptr==NULL)
//
// {
// throw exception("ptr is null");
// }
// *p=*ptr;
// //delete p'
//}
//int main()
//{
// func(NULL);
// return 0;
//}