You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.9 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#if !defined(__MY_SMART_PTR_TEMPLATE_H__)
#define __MY_SMART_PTR_TEMPLATE_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//自己的智能指针模板
template<typename TYPE>
class RefPtr
{
//该类成员访问权限全部为private因为不直接使用该类
template<typename TYPE> friend class Sptr;
RefPtr(TYPE *ptr):p(ptr), count(1) { }
~RefPtr() { delete p; }
TYPE *GetPtr(){return p;}
int count; //引用计数
TYPE *p; //基础对象指针
};
template<typename TYPE>
class Sptr
{
public:
Sptr(TYPE *ptr):rp(new RefPtr<TYPE>(ptr)) { } //构造函数
Sptr(const Sptr &sp):rp(sp.rp) { ++rp->count; } //复制构造函数
Sptr& operator=(const Sptr& rhs)
{ //重载赋值操作符
++rhs.rp->count; //首先将右操作数引用计数加1
if(--rp->count == 0) //然后将引用计数减1可以应对自赋值
delete rp;
rp = rhs.rp;
return *this;
}
~Sptr()
{
if(--rp->count == 0) //当引用计数减为0时删除辅助类对象指针从而删除基础对象
delete rp;
}
//重载操作符,模拟指针行为
TYPE &operator*() { return *rp->p; }
TYPE *operator->() { return rp->p; }
const TYPE &operator*() const { return *rp->p; }
const TYPE *operator->() const { return rp->p; }
TYPE *GetPtr(){return rp->GetPtr();}//获取管理的指针
bool IsNull()
{
if(rp->GetPtr())
return false;
else
return true;
}
private:
RefPtr<TYPE> *rp; //辅助类对象指针
};
#endif//__MY_SMART_PTR_TEMPLATE_H__