Last active
January 23, 2022 08:19
-
-
Save Drusy/9651531 to your computer and use it in GitHub Desktop.
Generic C++ Pool implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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