您的位置:首页 > 其它

智能指针

2016-04-19 21:02 239 查看
智能指针:是存储指向动态分配对象指针的类。能够在适当的时间自动删除指向的对象。
下面是它的三种实现:
//autoptr
template<class T>
class Autoptr
{
public:
Autoptr(T* ptr)
:_ptr(ptr)
{}
~Autoptr()
{
if(_ptr)
{
delete _ptr;
_ptr = NULL;
}
}
AutoPtr(const AutoPtr<T>& ap)
{
_ptr = ap._ptr;
ap._ptr = NULL;
}
AutoPtr& operator=(const AutoPtr<T>& ap)
{
if(this != &ap)
{
if(_ptr && _ptr!=ap._ptr)
delete _ptr;
_ptr = ap._ptr;
ap._ptr = NULL;
}
return *this;
}
T& operator*()
{
assert(_ptr);
return *_ptr;
}
T* operator->()
{
return _ptr;
}
T* Getptr()
{
return _ptr;
}
bool operator=(const AutoPtr<T>& ap)
{
if(ap._ptr == _ptr)
return true;
else
return false;
}
private:
T* _ptr;
};

//scopedptr
template<class T>
class Scopedptr
{
public:
Scopedptr(T* ptr)
:_ptr(ptr)
{}
~Scopedptr()
{
if(_ptr)
{
delete _ptr;
_ptr = NULL;
}
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
T* Getptr()
{
return _ptr;
}
Scopedptr(const Scopedptr<T>& ap);  //只声明不实现
Scopedptr& operator=(const Scopedptr<T>& ap);
private:
T* _ptr;

};
//引用计数
template<class T>
class Sharedptr
{
public:
Sharedptr(T* ptr)
:_ptr(ptr)
,_count(new int(1))
{}
~Sharedptr()
{
if(_ptr)
{
_Release();
_ptr = NULL;
_count = NULL;
}
}
SharedPtr(SharedPtr<T>& sp)
:_ptr(sp._ptr)
,_count(sp._count)
{

(*_count)++;
}
SharedPtr& operator=(const SharedPtr<T>& sp)
{
if(this != &ap)
{
_Release();
_ptr = sp._ptr;
_count = sp._count;
(*_count)++;
}
return *this;
}
private:
void _Release()
{
if((*_count)-- == 0)
{
delete _count;
delete _ptr;
}
}
private:
T* _ptr;
int* _count;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: