shared_ptr 共享对象所有权的智能指针
实现shared_ptr;
该智能指针不仅需要指向性,还需要知道和谁共享资源;因此需要RefCnt
class RefCnt{
_Ty* mptr;智能指针的指向;
int ref;//用于计数
}
template<class _Ty>
class MyDeletor
{
//MyDeletor()=default;->默认构造函数
MyDeletor() {}
void operatror()(_Ty* ptr)const
{
if (ptr != nullptr)
{
delete ptr;//调用delete时,会先调用析构函数
}
}
};
template<class _Ty>
class MyDeletor<_Ty[]>
{
//MyDeletor()=default;->默认构造函数
MyDeletor() {}
void operatror()(_Ty* ptr)const
{
if (ptr != nullptr)
{
delete[]ptr;//调用delete时,会先调用析构函数
}
}
};
删除器MyDeletor{};
template <class _Ty>
class RefCnt
{
public:
T* mptr;
int ref;//用于计数
public:
RefCnt(_Ty* ptr = nullptr) :mptr(ptr), ref(mptr != nullptr)
{
//ref=mptr==nullptr?0:1;
}
~RefCnt(){}
};