Extra2D/Extra2D/include/extra2d/core/object_pool.h

65 lines
1.3 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.

#pragma once
#include <extra2d/core/types.h>
#include <array>
#include <queue>
namespace extra2d {
/**
* @brief 固定大小对象池
* @tparam T 对象类型
* @tparam Size 池大小
*/
template <typename T, size_t Size>
class ObjectPool {
public:
ObjectPool() {
for (size_t i = 0; i < Size; ++i) {
available_.push(&pool_[i]);
}
}
/**
* @brief 获取对象
* @return 对象指针池耗尽返回nullptr
*/
T* acquire() {
if (available_.empty()) {
return nullptr;
}
T* obj = available_.front();
available_.pop();
return obj;
}
/**
* @brief 释放对象回池
* @param obj 对象指针
*/
void release(T* obj) {
if (obj >= pool_.data() && obj < pool_.data() + Size) {
obj->~T();
new (obj) T();
available_.push(obj);
}
}
/**
* @brief 获取可用对象数量
*/
size_t available() const { return available_.size(); }
/**
* @brief 获取池总大小
*/
static constexpr size_t capacity() { return Size; }
private:
alignas(alignof(T)) std::array<u8, sizeof(T) * Size> storage_;
T* pool_ = reinterpret_cast<T*>(storage_.data());
std::queue<T*> available_;
};
} // namespace extra2d