shared_ptr:使用引用计数
- 传入指针的构造函数
- 拷贝构造函数
- 赋值函数
- 析构函数
- 获取引用计数
- ->和*的重载
注意事项
- 构造函数是explicit的,防止smart_ptr< int > sp = p 的使用
- 计数需要用int*
- *ptr++是先++的,所以需要括号或者++*ptr
smart_ptr.h
template<typename T>
class smart_ptr
{
T* ptr;
int* count;
public:
explicit smart_ptr(T* p);
smart_ptr(smart_ptr<T>& other);
smart_ptr<T>& operator=(smart_ptr<T>& other);
~smart_ptr();
int use_count();
T* operator->();
T& operator*();
};
smart_ptr.cpp
template<typename T>
smart_ptr<T>::smart_ptr(T* p):
ptr(p), count(new int(1)) {}
template<typename T>
smart_ptr<T>::smart_ptr(smart_ptr<T>& other)
{
if (ptr && --*count == 0)
{
delete ptr;
delete count;
}
++*other.count;
ptr = other.ptr;
count = other.count;
}
template<typename T>
smart_ptr<T>& smart_ptr<T>::operator=(smart_ptr<T>& other)
{
// TODO: insert return statement here
if (other.ptr != this->ptr)
{
if (ptr && --(*count) == 0)
{
delete ptr;
delete count;
}
ptr = other.ptr;
count = other.count;
++*count;
}
return *this;
}
template<typename T>
smart_ptr<T>::~smart_ptr()
{
if (ptr && --*count == 0)
{
delete ptr;
delete count;
}
ptr = nullptr;
count = nullptr;
}
template<typename T>
int smart_ptr<T>::use_count()
{
if (count)
return *count;
else
return 0;
}
template<typename T>
T* smart_ptr<T>::operator->()
{
return ptr;
}
template<typename T>
T& smart_ptr<T>::operator*()
{
return *ptr;
}