// auto_ptrTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
namespace GQ
{
template<typename T>
class auto_ptr
{
public:
template<class Y>
struct auto_ptr_ref
{
Y* yp;
explicit auto_ptr_ref(Y* rhs):yp(rhs){}
};
typedef T element_type;
explicit auto_ptr(T*ptr = NULL)throw() //屏蔽掉隐式构造
{
ap = ptr;
} // auto_ptr<int >obj = new int(10);//error auto_ptr<int>obj(new int(10))//right
auto_ptr(auto_ptr&)throw();
template<class U>
auto_ptr(auto_ptr<U>&ptr)throw() //将派生类对象传给基类时调用
{
ap = ptr.release();
}
//overrides
auto_ptr& operator=(auto_ptr &ptr)throw() //赋值转换
{
reset(ptr.release());
return *this;
}
template<class Y>
auto_ptr& operator =(auto_ptr<Y>& ptr)throw() //将派生类对象传给基类时调用
{
reset(ptr.release());
return *this;
}
T* get()const throw()
{
return ap;
}
T& operator*()const throw()
{
return *ap;
}
T* operator->()const throw() //使用初始化T类型中操作函数或数据成员
{
return ap;
}
//destruction
~auto_ptr() throw()
{
delete ap;
ap = NULL;
}
//member functions
//release ownership
T* release()throw();
// reset value
void reset(T* ptr = NULL)throw()
{
if(ap != ptr)
delete ap;
ap = ptr;
}
public:
auto_ptr(auto_ptr_ref<T>yp)throw() //auto_ptr_ref<T>相当于传入一个该类型实参
{
ap = yp.yp;
}
auto_ptr& operator=(auto_ptr_ref<T>rhs)throw()
{
reset(rhs.release());
return *this;
}
template<class U>operator auto_ptr_ref<U>() throw() //将auto_ptr convert to auto_ptr_ref
{
return auto_ptr_ref<U>(release());
}
template<class U>operator auto_ptr<U>()throw() //auto_ptr convert to auto_ptr
{
return auto_ptr<U>(release());
}
private:
T *ap;
};
//拷贝构造
template<class T>
auto_ptr<T>::auto_ptr(auto_ptr &ptr)throw()
{
ap = ptr.release();
}
//转移智能指针权限
template<class T>
T* auto_ptr<T>::release()throw()
{
T *pTemp(ap);
ap = NULL;
return pTemp;
}
};
class CA
{
public:
CA():m_nNum(0){cout<<"CA::CA()"<<endl;}
CA(int nNum):m_nNum(nNum){}
operator int()
{
return m_nNum;
}
private:
int m_nNum;
};
class CB:public CA
{
public:
CB(int nNum):m_nNum(nNum){cout<<"CB::CB(int nNum)"<<endl;}
void Fun()
{
cout<<"CB::Fun()"<<endl;
}
class CC;
private:
int m_nNum;
};
class CC
{
public:
CB &obj;
CC(CB&objB):obj(objB){ m_pC = this;}
/* CB* operator->()const
{
return &obj;
}*/
void Fun()
{
cout<<"CC::Fun()"<<endl;
}
private:
CC* m_pC;
};
int main(int argc, char* argv[])
{
GQ::auto_ptr<int>obj(new int(20)); //调用explicit auto_ptr(T*ptr = NULL)throw()
GQ::auto_ptr<int>::auto_ptr_ref<int>ref = obj; //调用类型转换符template<class U>operator auto_ptr_ref<U>() throw()
int nNum = 0;
if(NULL == obj.get())
{
cout<<"auto_ptr cast to auto_prt_ref 权限转换成功"<<endl;
}
GQ::auto_ptr<int>aObj(ref); //调用auto_ptr(auto_ptr_ref<T>yp)throw()
if(NULL != ref.yp)
{
cout<<"auto_prt_ref cast to auto_ptr:"<<*(int *)ref.yp<<endl;
}
CB objB(10);
GQ::auto_ptr<CC>objC(new CC(objB));
objC->Fun(); //调用 T* operator->()
return 0;
}
通用工具auto_ptr 模板智能指针
最新推荐文章于 2022-08-29 00:02:18 发布