Men的博客

欢迎光临!

0%

c++引用计数

智能指针:能够对内存进行进行自动管理,避免出现悬垂指针等情况。
引用计数可以跟踪对象所有权,并能够自动销毁对象。节省内存,提高程序运行效率。
智能指针的实现策略有两种:辅助类与句柄类
class SmartPtr
{
public:
SmartPtr(Point *ptr) : rp(new U_Ptr(ptr)) {}

SmartPtr(const SmartPtr &sp) : rp(sp.rp) { ++rp->count; }

SmartPtr &operator=(const SmartPtr &rhs)
{
++rhs.rp->count;
if (–rp->count == 0)
delete rp;
rp = rhs.rp;
return *this;
}

int getCount() {
return rp->count;
}

~SmartPtr()
{
if (–rp->count == 0)
delete rp;
else
cout << “还有” << rp->count << “个指针指向基础对象” << endl;
}
xdl的实现
class RefCounted
{
public:
explicit RefCounted(int ref = 1) : ref_(ref) {}
virtual ~RefCounted() {}
void Ref()
{
ref_++;
}
void UnRef()
{
if (–ref_ == 0)
{
delete this;
}
}

int64_t getRef() {
return ref_;
}

private:
std::atomic ref_;
};

template
class RefCountedPtr
{
public:
RefCountedPtr() : ptr_(nullptr) {}

explicit RefCountedPtr(T *ptr) : ptr_(ptr)
{
Ref();
}

RefCountedPtr(const RefCountedPtr &rptr) : ptr_(rptr.ptr_)
{
Ref();
}

RefCountedPtr(RefCountedPtr &&rptr) : ptr_(rptr.ptr_)
{
rptr.ptr_ = nullptr;
}

RefCountedPtr &operator=(T *ptr)
{
UnRef();
ptr_ = ptr;
Ref();
return *this;
}

RefCountedPtr &operator=(const RefCountedPtr &rptr)
{
UnRef();
ptr_ = rptr.ptr_;
Ref();
return *this;
}

RefCountedPtr &operator=(RefCountedPtr &&rptr)
{
std::swap(ptr_, rptr.ptr_);
return *this;
}

~RefCountedPtr()
{
if (ptr_ != nullptr)
{
ptr_->UnRef();
}
}

std::add_lvalue_reference operator*() const
{
return *ptr_;
}

T *operator->() const
{
return ptr_;
}

T *get() const
{
return ptr_;
}

template <typename… Targs>
static RefCountedPtr Create(Targs &&… args)
{
return RefCountedPtr(new T(std::forward(args)…), 0);
}

private:
// for RefCountedPtr::Create
RefCountedPtr(T *ptr, int x) : ptr_(ptr)
{
(void)x;
}
void Ref()
{
if (ptr_ != nullptr)
{
ptr_->Ref();
}
}

void UnRef()
{
if (ptr_ != nullptr)
{
ptr_->UnRef();
}
}

T *ptr_;
};