#include <iostream>
#include <memory>
#include <atomic>
template<typename T>
class RefCount
{
public:
RefCount(T* t)
:ptr_(t),
count_(1) {}
void AddRef() {
count_ ++;
}
void DelRef() {
count_ --;
if (0 == count_) {
Destory();
}
}
long use_count() const { return count_;}
private:
void Destory() {
if (ptr_) {
delete ptr_;
ptr_ = nullptr;
}
}
private:
T * ptr_;
std::atomic_long count_;
};
template<typename T>
class SharedPtr
{
SharedPtr() {
ptr_ = nullptr;
count_ = nullptr;
}
SharedPtr(T *t)
:ptr_(t),
count_(new RefCount<T>(t)){}
~SharedPtr() {
if (count_) {
count_->DelRef();
ptr_ = nullptr;
}
count_ = nullptr;
}
//拷贝构造
SharedPtr(const SharedPtr<T>& right) {
if (right.ptr_) {
right.count_->AddRef();
}
ptr_ = right.ptr_;
count_ = right.count_;
}
//移动构造
SharedPtr(SharedPtr&& right) {
ptr_ = right.ptr_;
count_ = right.count_;
right.ptr_ = nullptr;
right.count_ = nullptr;
}
//赋值运算符
SharedPtr<T> & operator=(const SharedPtr<T>& right) {
right.count_->AddRef();
if (count_) {
count_->DelRef();
}
count_ = right.count_;
ptr_ = right.ptr_;
return (*this);
}
SharedPtr<T> operator=(SharedPtr<T>&& right) {
= std::move 会调用移动构造函数,t获得right的数据所有权,right失去数据所有权
SharedPtr<T> t = std::move(right);
//交换t和this,然后t在函数退出时清理掉,会让原本this指向的对象计数减1
t.swap(*this);
return (*this);
}
void Swap(SharedPtr<T>& right) {
std::swap(this->count_,right.count_);
std::swap(this->ptr_,right.ptr_);
}
T* get() { return ptr_;}
T* operator->() { return get();}
long use_count() { count_ ? count_->use_count():0;}
private:
T * ptr_ = nullptr;
RefCount<T> * count_ = nullptr;
};
int main()
{
return 0;
}
线程安全的shareptr 简单实现
最新推荐文章于 2023-11-13 19:18:49 发布