dl
dl_object_pool.h
浏览该文件的文档.
1
12
13#pragma once
14#include <vector>
15#include <stack>
16
17namespace dl
18{
19
21template<typename T>
23{
24public:
25 // 申请一个空闲元素(O(1))
26 size_t GetFree()
27 {
28 // 1. 优先用空闲列表
29 if (!_freeIndex.empty())
30 {
31 size_t idx = _freeIndex.top();
32 _freeIndex.pop();
33 return idx;
34 }
35
36 // 2. 无空闲 → 扩容(最多触发一次)
37 _data.emplace_back();
38 return _data.size() - 1;
39 }
40
41 // 释放元素(O(1))
42 void Release(size_t index)
43 {
44 if (index < _data.size())
45 {
46 _freeIndex.push(index);
47 }
48 }
49
50 // 访问元素
51 T& operator[](size_t index)
52 {
53 return _data[index];
54 }
55
56 // 获取全部数据
57 std::vector<T>& data()
58 {
59 return _data;
60 }
61
62private:
63 std::vector<T> _data; // 真实资源
64 std::stack<size_t> _freeIndex; // 空闲索引栈
65};
66
67
69template<typename T>
71{
72public:
74 {
75 /*slots.resize(capacity);
76 freeList.reserve(capacity);
77 liveList.reserve(capacity);
78 for (uint32_t i = 0; i < capacity; ++i)
79 {
80 freeList.push_back(capacity - 1 - i);
81 slots[i].isActive = false;
82 }*/
83 }
84
86 {
87 if (freeList.empty())
88 _extend();
89
90 uint32_t idx = freeList.back();
91 freeList.pop_back();
92
93 slots[idx].isActive = true;
94 slots[idx].liveIndex = liveList.size();
95 liveList.push_back(idx);
96
97 return &slots[idx].data;
98 }
99
100 void release(T* ptr) {
101 uint32_t idx = static_cast<uint32_t>(ptr - &slots[0].data);
102 if (!slots[idx].isActive) return;
103
104 // O(1) 从 liveList 移除
105 uint32_t lastIdx = liveList.back();
106 uint32_t removePos = slots[idx].liveIndex;
107
108 liveList[removePos] = lastIdx;
109 slots[lastIdx].liveIndex = removePos;
110 liveList.pop_back();
111
112 slots[idx].isActive = false;
113 freeList.push_back(idx);
114 }
115
116 size_t aliveCount() const
117 {
118 return liveList.size();
119 }
120
121private:
122 struct Slot
123 {
124 T data;
125 uint32_t liveIndex;
126 bool isActive;
127 };
128
129 std::vector<Slot> slots;
130 std::vector<uint32_t> freeList;
131 std::vector<uint32_t> liveList;
132
133 void _extend()
134 {
135 Slot slot;
136 slot.isActive = false;
137 slots.push_back(slot);
138 freeList.push_back(slots.size() - 1);
139 }
140};
141}
size_t aliveCount() const
T & operator[](size_t index)
std::vector< T > & data()
void Release(size_t index)