要实现一个智能指针主要实现下面几个函数
1 构造函数
2 拷贝构造函数
3 析构函数
4 赋值运算符函数
5 获取引用计数函数
重点
:
1 构造,拷贝构造 +1
2 析构函数会使引用计数-1.
3 赋值运算符会使之前的引用计数-1。使新赋值过来的引用计数+1
#include <iostream>
template<class T>
class SmartPtr
{
public:
SmartPtr(T* p = nullptr)
{
ptr = p;
if (p == nullptr)
ref_count = new int(0);
else
ref_count = new int(1);
}
~SmartPtr()
{
if (ptr)
{
if (--(*ref_count) == 0)
{
delete ptr;
delete ref_count;
}
}
}
SmartPtr(const SmartPtr& s)
{
ptr = s.ptr;
ref_count = s.ref_count;
(*ref_count)++;
}
SmartPtr& operator=(const SmartPtr& s)
{
if (ptr == s.ptr)
return *this;
if (ptr)
{
if (--(*ref_count) == 0)
{
delete ptr;
delete ref_count;
}
}
ptr = s.ptr;
ref_count = s.ref_count;
(*ref_count)++;
return *this;
}
T* operator->()
{
return ptr;
}
SmartPtr& operator*()
{
return *this;
}
int use_count()
{
return *ref_count;
}
private:
T* ptr;
int *ref_count;
};
int main()
{
{
int *arry = new int[3];
SmartPtr<int> sp(arry);
SmartPtr<int> sp1;
sp1 = sp;
SmartPtr<int> sp2(sp1);
sp1.use_count();
}
std::cout << "end" << std::endl;
return 0;
}