Extra2D/include/core/ref_counted.h

42 lines
899 B
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.

#pragma once
#include <atomic>
#include <cstdint>
namespace extra2d {
// ============================================================================
// 侵入式引用计数基类
// 参考 Cocos2d-x 的 RefCounted 设计
// ============================================================================
class RefCounted {
public:
virtual ~RefCounted() = default;
// 增加引用计数
void addRef() {
++_referenceCount;
}
// 减少引用计数当计数为0时删除对象
void release() {
if (--_referenceCount == 0) {
delete this;
}
}
// 获取当前引用计数
uint32_t getRefCount() const {
return _referenceCount.load();
}
protected:
// 构造函数初始引用计数为1
RefCounted() : _referenceCount(1) {}
private:
std::atomic<uint32_t> _referenceCount;
};
} // namespace extra2d