141 lines
2.2 KiB
C++
141 lines
2.2 KiB
C++
/**
|
||
* @file dl_object_pool.h
|
||
* @brief 对象池
|
||
*
|
||
|
||
* @version 1.1
|
||
* @author lveyou
|
||
* @date 26-05-08
|
||
*
|
||
* @note 对象自动进行析构和构造调用
|
||
*/
|
||
|
||
#pragma once
|
||
#include <vector>
|
||
#include <stack>
|
||
|
||
namespace dl
|
||
{
|
||
|
||
//! 对象池
|
||
template<typename T>
|
||
class ObjectPool
|
||
{
|
||
public:
|
||
// 申请一个空闲元素(O(1))
|
||
size_t GetFree()
|
||
{
|
||
// 1. 优先用空闲列表
|
||
if (!_freeIndex.empty())
|
||
{
|
||
size_t idx = _freeIndex.top();
|
||
_freeIndex.pop();
|
||
return idx;
|
||
}
|
||
|
||
// 2. 无空闲 → 扩容(最多触发一次)
|
||
_data.emplace_back();
|
||
return _data.size() - 1;
|
||
}
|
||
|
||
// 释放元素(O(1))
|
||
void Release(size_t index)
|
||
{
|
||
if (index < _data.size())
|
||
{
|
||
_freeIndex.push(index);
|
||
}
|
||
}
|
||
|
||
// 访问元素
|
||
T& operator[](size_t index)
|
||
{
|
||
return _data[index];
|
||
}
|
||
|
||
// 获取全部数据
|
||
std::vector<T>& data()
|
||
{
|
||
return _data;
|
||
}
|
||
|
||
private:
|
||
std::vector<T> _data; // 真实资源
|
||
std::stack<size_t> _freeIndex; // 空闲索引栈
|
||
};
|
||
|
||
|
||
//! 对象池
|
||
template<typename T>
|
||
class ObjectPoolEx
|
||
{
|
||
public:
|
||
ObjectPoolEx()
|
||
{
|
||
/*slots.resize(capacity);
|
||
freeList.reserve(capacity);
|
||
liveList.reserve(capacity);
|
||
for (uint32_t i = 0; i < capacity; ++i)
|
||
{
|
||
freeList.push_back(capacity - 1 - i);
|
||
slots[i].isActive = false;
|
||
}*/
|
||
}
|
||
|
||
T* acquire()
|
||
{
|
||
if (freeList.empty())
|
||
_extend();
|
||
|
||
uint32_t idx = freeList.back();
|
||
freeList.pop_back();
|
||
|
||
slots[idx].isActive = true;
|
||
slots[idx].liveIndex = liveList.size();
|
||
liveList.push_back(idx);
|
||
|
||
return &slots[idx].data;
|
||
}
|
||
|
||
void release(T* ptr) {
|
||
uint32_t idx = static_cast<uint32_t>(ptr - &slots[0].data);
|
||
if (!slots[idx].isActive) return;
|
||
|
||
// O(1) 从 liveList 移除
|
||
uint32_t lastIdx = liveList.back();
|
||
uint32_t removePos = slots[idx].liveIndex;
|
||
|
||
liveList[removePos] = lastIdx;
|
||
slots[lastIdx].liveIndex = removePos;
|
||
liveList.pop_back();
|
||
|
||
slots[idx].isActive = false;
|
||
freeList.push_back(idx);
|
||
}
|
||
|
||
size_t aliveCount() const
|
||
{
|
||
return liveList.size();
|
||
}
|
||
|
||
private:
|
||
struct Slot
|
||
{
|
||
T data;
|
||
uint32_t liveIndex;
|
||
bool isActive;
|
||
};
|
||
|
||
std::vector<Slot> slots;
|
||
std::vector<uint32_t> freeList;
|
||
std::vector<uint32_t> liveList;
|
||
|
||
void _extend()
|
||
{
|
||
Slot slot;
|
||
slot.isActive = false;
|
||
slots.push_back(slot);
|
||
freeList.push_back(slots.size() - 1);
|
||
}
|
||
};
|
||
} |