Skip to content

Instantly share code, notes, and snippets.

@Drusy
Last active January 23, 2022 08:19
Show Gist options
  • Save Drusy/9651531 to your computer and use it in GitHub Desktop.
Save Drusy/9651531 to your computer and use it in GitHub Desktop.
Generic C++ Pool implementation
#ifndef POOL_H
#define POOL_H
#include <list>
#include <iostream>
using namespace std;
template<typename T>
class Pool
{
public:
Pool();
~Pool();
T* take();
void back(T* object);
protected:
unsigned count;
list<T*> objects;
};
template<typename T>
Pool<T>::Pool() {
count = 0;
}
template<typename T>
Pool<T>::~Pool() {
typename list<T*>::iterator i = objects.begin();
while(i != objects.end())
{
delete (*i);
++i;
}
}
template<typename T>
T* Pool<T>::take() {
if (count != 0) {
T* object = objects.back();
objects.pop_back();
--count;
object->init();
return object;
}
return new T();
}
template<typename T>
void Pool<T>::back(T* object) {
objects.push_back(object);
++count;
}
#endif // POOL_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment