Skip to content

Instantly share code, notes, and snippets.

@swarminglogic
Last active June 26, 2022 14:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swarminglogic/b83993196eaf2ed18bf1 to your computer and use it in GitHub Desktop.
Save swarminglogic/b83993196eaf2ed18bf1 to your computer and use it in GitHub Desktop.
SmartObjectPool: A RAII-style implementation of the object pool pattern that uses smart pointers to automatically return acquired objects to the pool when deleted.
#include <memory>
#include <stack>
#include <stdexcept>
template <class T, class D = std::default_delete<T>>
class SmartObjectPool
{
private:
struct ReturnToPool_Deleter {
explicit ReturnToPool_Deleter(std::weak_ptr<SmartObjectPool<T, D>* > pool)
: pool_(pool) {}
void operator()(T* ptr) {
if (auto pool_ptr = pool_.lock())
(*pool_ptr.get())->add(std::unique_ptr<T, D>{ptr});
else
D{}(ptr);
}
private:
std::weak_ptr<SmartObjectPool<T, D>* > pool_;
};
public:
using ptr_type = std::unique_ptr<T, ReturnToPool_Deleter >;
SmartObjectPool() : this_ptr_(new SmartObjectPool<T, D>*(this)) {}
virtual ~SmartObjectPool(){}
void add(std::unique_ptr<T, D> t) {
pool_.push(std::move(t));
}
ptr_type acquire() {
if (pool_.empty())
throw std::out_of_range("Cannot acquire object from an empty pool.");
ptr_type tmp(pool_.top().release(),
ReturnToPool_Deleter{
std::weak_ptr<SmartObjectPool<T, D>*>{this_ptr_}});
pool_.pop();
return std::move(tmp);
}
bool empty() const {
return pool_.empty();
}
size_t size() const {
return pool_.size();
}
private:
std::shared_ptr<SmartObjectPool<T, D>* > this_ptr_;
std::stack<std::unique_ptr<T, D> > pool_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment