Class template to create pool of objects

[ permalink ] [ download ]
/*
*	Author: Jon Ander Ortiz
*	License: GPLV2 or Later
*
*	Brief:
*	Template for Creating a pool of objects.
*	The templates overloads the new and delete operators of the 
*	pooled class, so it controls the creation and deletion of them.
*	The instances of the objects when they are deleted, 
*	are pooled for further use when there is a new done, so those 
*	operations are not done ^_^
* 	Especially recommended for high-use objects
*/
#include <iostream>

#define POOL_MAX(nombre,val) (Pool<nombre>::max = val)

template <class T> class Pool {
protected:
	int data;
	Pool* next;
	Pool* last;
	static Pool * freelist;
	static long counter; 
public:
	static long max;
	Pool();
    ~Pool();
	void* operator new(size_t);     
	void operator delete(void*);    
};


template <class T> Pool<T>::Pool(){}
template <class T> Pool<T>::~Pool(){
	//Pending to implement the delete of the pooled elements!!!! BE CAREFULL!!! 
	//This example is just an experiment ^_^ 
}

template <class T> inline void* Pool<T>::operator new(size_t sz)
{
    if (Pool<T>::freelist) {
    Pool * p = Pool<T>::freelist;
    Pool<T>::freelist = Pool<T>::freelist->next;
    return p;
	}
    return malloc(sz);
}

template <class T> inline void Pool<T>::operator delete(void* vp)
{
	Pool* p = (Pool*)vp;
	// link freed node onto freelist
	if (Pool<T>::counter < Pool<T>::max)
	{	
		p->next = Pool<T>::freelist;
		Pool<T>::freelist = p;
		++Pool<T>::counter;
	}
}
// From here to the end only is the example
template<class T> long Pool<T>::max =1;
template<class T> long Pool<T>::counter =0;
template<class T> Pool<T>* Pool<T>::freelist = NULL; 
/*
Whe should reserve space for the static vars, if we don´t do this, the 
compiler don´t assigns memory to them and it will crash if we
access those members.
*/


class A {
public:
	std::string s;
};
const int N = 1000;
typedef Pool<std::string> PooledString;
typedef Pool<A> PooledA;
int main()
{

	PooledString * aptr[N];
	PooledA * a = new PooledA();
	POOL_MAX(std::string, 10);  //Define with that macro the max
								//number of instances in the POOL
	POOL_MAX(A, 2);
	int i;
    int j;
	// repeatedly allocate / deallocate A objects
    for (i = 1; i <= N; i++) {
         for (j = 0; j < N; j++)
             aptr[j] = new PooledString();
         for (j = 0; j < N; j++)
              delete aptr[j];
    }
	return 0;
}
hits counter