这是一个简单易用的对象池,很多系统对资源的访问快捷性及可预测性有严格要求,列入包括网络连接、对象实例、线程和内存。而且还要求解决方案可扩展,能应付存在大量资源的情形。
object pool针对特定类型的对象循环利用,这些对象要么创建开销巨大,要么可创建的数量有限。而且在pool中的对象需要做到无状态。
如何使用
utility::object_pool_t<int> pool1([]()
{
return std::make_shared<int>(10);
});
{
auto t = pool1.get();
}
指定类型,创建一个pool对象,同时提供创建对象函数。
获取接口get,返回一个std::shared_ptr<T>对象,在该对象析构时自动返回到pool中,不需要额外的释放接口
实现
#ifndef __UTILITY_OBJECT_POOL_HPP
#define __UTILITY_OBJECT_POOL_HPP
#include <memory>
#include <list>
#include <functional>
#include <cstdint>
namespace utility {
template < typename T >
struct object_pool_traits_t;
template < typename T, typename