//
// Created by krislyy on 2018/11/14.
//
#ifndef ALGORITHM_OBJECTPOOL_H
#define ALGORITHM_OBJECTPOOL_H
#include <vector>
#include <memory>
#include <functional>
template<typename T>
class ObjectPool
{
public:
using DeleterType = std::function<void(T*)>;
void add(std::unique_ptr<T> t)
{
m_pool.emplace_back(std::move(t));
}
std::unique_ptr<T, DeleterType> get()
{
if (m_pool.empty())
{
throw std::logic_error("No more object");
}
std::unique_ptr<T, DeleterType> ptr(m_pool.back().release(), [this](T* t)
{
m_pool.emplace_back(std::unique_ptr<T>(t));
});
m_pool.pop_back();
return std::move(ptr);
}
std::shared_ptr<T> getShared()
{
if (m_pool.empty())
{
throw std::logic_error("No more object");
}
auto pin = std::unique_ptr<T>(std::move(m_pool.back()));
m_pool.pop_back();
return std::shared_ptr<T>(pin.release(), [this](T* t)
{
m_pool.emplace_back(std::unique_ptr<T>(t));
});
}
bool empty() const
{
return m_pool.empty();
}
std::size_t size() const
{
return m_pool.size();
}
private:
std::vector<std::unique_ptr<T>> m_pool;
};
#endif //ALGORITHM_OBJECTPOOL_H
測(cè)試案例
template <typename T>
class Object
{
T data;
public:
Object(T n) : data(n){
}
void print()
{
std::cout << "Hello world: " << data << std::endl;
}
};
void checkObjectPool() {
typedef Object<int> ObjectInt;
ObjectPool<ObjectInt> pool;
pool.add(std::unique_ptr<Object<int>>(new Object<int>(1)));
pool.add(std::unique_ptr<Object<int>>(new Object<int>(2)));
std::cout << "Object pool size: " << pool.size() << std::endl;
{
auto obj = pool.get();
obj->print();
{
auto obj2 = pool.get(); //隨即就被釋放了
}
std::cout << "Object pool size: " << pool.size() << std::endl;
}
std::cout << "Object pool size: " << pool.size() << std::endl;
}