Skip to content

Instantly share code, notes, and snippets.

@binshuohu
Created November 27, 2015 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save binshuohu/5d49cfa80cf8b91743ee to your computer and use it in GitHub Desktop.
Save binshuohu/5d49cfa80cf8b91743ee to your computer and use it in GitHub Desktop.
simple object pool
#include <memory>
#include <vector>
#include <functional>
#include <iostream>
template <class T>
class SimpleObjectPool
{
public:
using DeleterType = std::function<void(T*)>;
void add(std::unique_ptr<T> t)
{
pool_.push_back(std::move(t));
}
std::shared_ptr<T> get()
{
if (pool_.empty())
{
throw std::logic_error("no more object");
}
auto pin = std::unique_ptr<T>(std::move(pool_.back()));
pool_.pop_back();
return std::shared_ptr<T>(pin.release(), [this](T* t)
{
pool_.push_back(std::unique_ptr<T>(t));
});
}
bool empty() const
{
return pool_.empty();
}
size_t size() const
{
return pool_.size();
}
private:
std::vector<std::unique_ptr<T>> pool_;
};
struct A
{
A(){ std::cout << "A ctor" << std::endl; }
~A(){ std::cout << "A dtor" << std::endl; }
};
//test code
void test_object_pool()
{
SimpleObjectPool<A> p;
p.add(std::unique_ptr<A>(new A()));
p.add(std::unique_ptr<A>(new A()));
{
auto t = p.get();
p.get();
}
{
p.get();
p.get();
}
std::cout << p.size() << std::endl;
}
int main()
{
test_object_pool();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment