template<class T>
class sharedptr
{
public:
sharedptr(T* ptr)
:_ptr(ptr)
, _refCount(new int(1))
{}
sharedptr(sharedptr<T>& sp)
:_ptr(sp._ptr)
, _refCount(sp._refCount)
{
++(*_refCount);
}
sharedptr& operator = (sharedptr<T>& sp) //现代写法
{
swap(_ptr, sp._ptr);
swap(_refCount, sp._refCount);
return *this;
}
/*sharedptr& operator = (sharedptr<T>& sp)
{
if (this != &sp)
{
this->Release();
_ptr = sp._ptr;
_refCount = sp._refCount;
++(*_refCount);
}
return *this;
}*/
void Release()
{
if (--(*_refCount) == 0)
{
delete _ptr;
delete _refCount;
}
}
~sharedptr()
{
Release();
}
private:
T* _ptr;
int* _refCount;
};
template<class T>
struct Delete
{
void operator()(T* ptr)
{
delete ptr;
}
};
template<class T>
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
template<class T> //定制删除器
struct Delete
{
void operator()(T* ptr)
{
delete ptr;
}
};
template<class T>//定制删除器
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
template<class T, class D = Delete<T>>
class sharedptr
{
public:
sharedptr(T* ptr, D del)
:_ptr(ptr)
, _refCount(new int(1))
, _del(del)
{}
sharedptr(sharedptr<T>& sp)
:_ptr(sp._ptr)
, _refCount(sp._refCount)
{
++(*_refCount);
}
sharedptr& operator = (sharedptr<T>& sp) //现代写法
{
swap(_ptr, sp._ptr);
swap(_refCount, sp._refCount);
return *this;
}
/*sharedptr& operator = (sharedptr<T>& sp)
{
if (this != &sp)
{
this->Release();
_ptr = sp._ptr;
_refCount = sp._refCount;
++(*_refCount);
}
return *this;
}*/
void Release()
{
if (--(*_refCount) == 0)
{
printf("delete:0x%p\n", _ptr);
_del(_ptr);
delete _refCount;
}
}
~sharedptr()
{
Release();
}
private:
T* _ptr;
int* _refCount;
D _del;
};
void TextSharedptr()
{
DeleteArray<int> da;
sharedptr<int, DeleteArray<int>> sp(new int[3], da);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有