87 lines
1.7 KiB
C++
87 lines
1.7 KiB
C++
|
|
#include "Tool/RefObject.h"
|
|||
|
|
|
|||
|
|
RefObject::RefObject()
|
|||
|
|
: ref_count_(0) // 修正:新创建对象引用计数应为1
|
|||
|
|
{
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
RefObject::~RefObject() {}
|
|||
|
|
|
|||
|
|
void RefObject::Retain()
|
|||
|
|
{
|
|||
|
|
// 修正:使用fetch_add确保原子操作
|
|||
|
|
ref_count_.fetch_add(1, std::memory_order_relaxed);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void RefObject::Release()
|
|||
|
|
{
|
|||
|
|
// 修正:使用fetch_sub确保原子操作并检查结果
|
|||
|
|
if (ref_count_.fetch_sub(1, std::memory_order_acq_rel) == 1)
|
|||
|
|
{
|
|||
|
|
delete this;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
uint32_t RefObject::GetRefCount() const
|
|||
|
|
{
|
|||
|
|
return ref_count_.load(std::memory_order_relaxed);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void *RefObject::operator new(size_t size)
|
|||
|
|
{
|
|||
|
|
void *ptr = memory::Alloc(size);
|
|||
|
|
if (!ptr)
|
|||
|
|
{
|
|||
|
|
throw std::bad_alloc();
|
|||
|
|
}
|
|||
|
|
return ptr;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void RefObject::operator delete(void *ptr)
|
|||
|
|
{
|
|||
|
|
if (ptr) // 增加空指针检查
|
|||
|
|
{
|
|||
|
|
memory::Free(ptr);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 修正:添加noexcept说明符,与声明一致
|
|||
|
|
void *RefObject::operator new(size_t size, std::nothrow_t const &) noexcept
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
return memory::Alloc(size);
|
|||
|
|
}
|
|||
|
|
catch (...)
|
|||
|
|
{
|
|||
|
|
return nullptr;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 修正:添加noexcept说明符,与声明一致
|
|||
|
|
void RefObject::operator delete(void *ptr, std::nothrow_t const &) noexcept
|
|||
|
|
{
|
|||
|
|
if (ptr) // 增加空指针检查
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
memory::Free(ptr);
|
|||
|
|
}
|
|||
|
|
catch (...)
|
|||
|
|
{
|
|||
|
|
// 忽略异常,符合noexcept语义
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 修正:添加noexcept说明符,与声明一致
|
|||
|
|
void *RefObject::operator new(size_t size, void *ptr) noexcept
|
|||
|
|
{
|
|||
|
|
return ::operator new(size, ptr);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void RefObject::operator delete(void *ptr, void *place) noexcept
|
|||
|
|
{
|
|||
|
|
::operator delete(ptr, place);
|
|||
|
|
}
|