template <typename T>
class SharedPtr{
public:
SharedPtr() = delete;//不允许未初始化的智能指针,防止使用空指针
SharedPtr(const SharedPtr&) noexcept; //拷贝构造
SharedPtr(T*) noexcept; //shallow copy
SharedPtr& operator=(const SharedPtr<T>) noexcept;//重载运算符
T& operator*() noexcept;
T* operator->() noexcept;
~SharedPtr();//析构函数
private:
T *ptr;//原始指针
int *use_count;//引用计数
};
template <typename T>
SharedPtr<T>::SharedPtr(T* ptr) noexcept:ptr(ptr), use_count(new int(1))
{}
template <typename T>
SharedPtr<T>::SharedPtr(const SharedPtr &s_ptr) noexcept {
ptr =s_ptr.ptr;
use_count = s_ptr.use_count;
++(*use_count);
}
template <typename T>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr<T> rhs) noexcept {
//考虑自我赋值的情况
if(rhs.ptr == this->ptr){
return *this;
}
//待拷贝智能指针引用数加1
++(*rhs.use_count);
//原智能指针引用计数减1,如果减一后引用计数为0就清楚所指向的资源
if(0 == --(use_count)){
delete ptr;
delete use_count;
std::cout << "deconstruct" << std::endl;
}
ptr = rhs.ptr;
use_count = rhs.use_count;
return *this;
}
template <typename T>
T& SharedPtr<T>::operator*() noexcept{
return *this->ptr;
}
template <typename T>
T* SharedPtr<T>::operator->() noexcept{
return this->ptr;
}
template <typename T>
SharedPtr<T>::~SharedPtr(){
if(0 == --(*use_count)){
delete ptr;
delete use_count;
}
}
一个简单引用计数智能指针的实现
最新推荐文章于 2023-09-18 16:09:54 发布