Refactored ObjectPool to correctly handle custom deleters

This commit is contained in:
Daniel Wolf 2016-09-21 10:22:46 +02:00
parent d97c880754
commit eea1eb381c
1 changed files with 11 additions and 13 deletions

View File

@ -4,30 +4,28 @@
#include <stack> #include <stack>
#include <mutex> #include <mutex>
template <class T> template <typename value_type, typename pointer_type = std::unique_ptr<value_type>>
class ObjectPool { class ObjectPool {
public: public:
using ptr_type = std::unique_ptr<T, std::function<void(T*)>>; using wrapper_type = lambda_unique_ptr<value_type>;
ObjectPool(std::function<std::unique_ptr<T>()> createObject) : ObjectPool(std::function<pointer_type()> createObject) :
createObject(createObject) createObject(createObject)
{} {}
virtual ~ObjectPool() {} wrapper_type acquire() {
ptr_type acquire() {
std::lock_guard<std::mutex> lock(poolMutex); std::lock_guard<std::mutex> lock(poolMutex);
if (pool.empty()) { if (pool.empty()) {
pool.push(createObject()); pool.push(createObject());
} }
ptr_type tmp(pool.top().release(), [this](T* p) { auto pointer = pool.top();
std::lock_guard<std::mutex> lock(poolMutex);
this->pool.push(std::unique_ptr<T>(p));
});
pool.pop(); pool.pop();
return std::move(tmp); return wrapper_type(pointer.get(), [this, pointer](value_type*) {
std::lock_guard<std::mutex> lock(poolMutex);
this->pool.push(pointer);
});
} }
bool empty() const { bool empty() const {
@ -41,7 +39,7 @@ public:
} }
private: private:
std::function<T*()> createObject; std::function<pointer_type()> createObject;
std::stack<std::unique_ptr<T>> pool; std::stack<std::shared_ptr<value_type>> pool;
mutable std::mutex poolMutex; mutable std::mutex poolMutex;
}; };