对象池通过预分配对象并重复使用来减少new/delete开销。实现包含初始化、获取acquire和回收release对象,用栈管理空闲对象,支持线程安全及后续优化如自动扩容与placement new。

对象池的核心目标是减少频繁创建和销毁对象带来的性能开销。C++中实现一个简单的对象池,关键在于预先分配一批对象,使用时从池中获取,用完后归还,而不是直接 delete 和 new。下面是一个简洁、实用的对象池设计与实现方式。
基本设计思路
对象池通常包含以下几个核心功能:
- 预先创建一组对象并维护在空闲列表中
- 提供获取对象的接口(从空闲列表取出)
- 提供回收对象的接口(放回空闲列表)
- 线程安全可选(根据使用场景决定是否加锁)
简单对象池实现代码
#include <vector>
#include <stack>
#include <mutex>
#include <stdexcept>
<p>template <typename T>
class ObjectPool {
private:
std::stack<T<em>> free_list;
std::vector<T</em>> all_objects;
std::mutex pool_mutex;</p><p>public:
// 构造时预分配 n 个对象
explicit ObjectPool(size_t n = 10) {
all_objects.reserve(n);
for (size_t i = 0; i < n; ++i) {
all_objects.push_back(new T());
}
for (auto it = all_objects.rbegin(); it != all_objects.rend(); ++it) {
free_list.push(*it);
}
}</p><pre class='brush:php;toolbar:false;'>// 非拷贝构造
ObjectPool(const ObjectPool&) = delete;
ObjectPool& operator=(const ObjectPool&) = delete;
~ObjectPool() {
for (auto obj : all_objects) {
delete obj;
}
}
// 获取一个可用对象
T* acquire() {
std::lock_guard<std::mutex> lock(pool_mutex);
if (free_list.empty()) {
// 可选择扩容,或抛出异常
throw std::runtime_error("ObjectPool exhausted");
}
T* obj = free_list.top();
free_list.pop();
return obj;
}
// 回收对象
void release(T* obj) {
std::lock_guard<std::mutex> lock(pool_mutex);
free_list.push(obj);
}};
使用示例
假设我们有一个需要频繁创建的小对象 Connection:
立即学习“C++免费学习笔记(深入)”;
struct Connection {
int id;
bool connected = false;
<pre class='brush:php;toolbar:false;'>Connection() { static int counter = 0; id = ++counter; }
void connect() { connected = true; }
void disconnect() { connected = false; }};
// 使用对象池 int main() { ObjectPool<Connection> pool(5);
auto* conn1 = pool.acquire(); conn1->connect(); std::cout << "Using connection " << conn1->id << "\n"; pool.release(conn1); // 用完归还 auto* conn2 = pool.acquire(); // 可能是同一个地址 std::cout << "Reused: " << conn2->id << "\n"; return 0;
}
注意事项与优化方向
这个简单实现适合大多数基础场景,但可根据需求进一步改进:
- 自动扩容:acquire 时若无可用对象,动态 new 一个,并加入 all_objects
- 构造参数支持:使用 variadic template 支持带参构造
- 内存对齐与 placement new:更高级实现可用原始内存 + placement new,避免提前构造无用对象
- 线程安全开关:单线程场景可移除 mutex 提升性能
基本上就这些。一个轻量级对象池不需要太复杂,关键是控制资源生命周期,提升性能。











