template <type T> class SmartPointer
{
public:
SmartPointer(T* ptr)
{
ref = ptr;
ref_count = (unsigned*)malloc(sizeof(unsigned));
*ref_count = 1;
}
SmartPointer(SmartPointer<T>& sptr)
{
ref = sptr.ref;
ref_count = sptr.ref_count;
++(*ref_count);
}
SmartPointer<T>& operator = (SmartPointer<T>& sptr)
{
if (this == &sptr)
{
return *this;
}
if (*ref_count > 0)
{
remove();
}
ref = sptr.ref;
ref_count = sptr.ref_count;
++(*ref_count);
return *this;
}
~SmartPointer()
{
remove();
}
T getValue()
{
return *ref;
}
protected:
void remove()
{
--(*ref_count);
if (*ref_count == 0)
{
delete ref;
free(ref_count);
ref = nullptr;
ref_count = nullptr;
}
}
T* ref;
unsigned* ref_count;
};
实现一个智能指针类
最新推荐文章于 2022-07-11 10:42:49 发布