SwitchGame/source/Tool/RefObject.cpp

87 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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);
}