CMemoryPool.h
//-----------------------------------------------------------------------------
// $Header: /tmp_mnt/asis/offline/ceres/cool/project/RCS/CMemoryPool.h,v 2.1 1996/10/04 08:46:02 voigt Exp $
//
// COOL Program Library
// Copyright (C) CERES collaboration, 1996
//
// Declaration of CMemoryPool class.
// It should be used if a large number of small objects has to be
// frequently allocated from heap. It is much more efficient and
// faster than the standard new/delete operators.
// Add to the referring class X the following lines:
//
// class X {
// public:
// void* operator new(size_t) { return pool.alloc(); }
// void operator delete(void* p) { pool.free(p); }
// // ...
// privat:
// static CMemoryPool pool;
// // ...
// }
//
// CMemoryPool X::pool(sizeof(X));
//
// Note that the class is optimized for speed and compactness
// not for readability. Only single objects may be created,
// i.e, new X[100] will not work; however, in these cases the
// default operators new/delete will be called.
//
//-----------------------------------------------------------------------------
#ifndef CMEMORYPOOL_H
#define CMEMORYPOOL_H
class CMemoryPool {
public:
CMemoryPool(unsigned);
~CMemoryPool();
inline void* alloc();
inline void free(void*);
private:
CMemoryPool(); // default protection
CMemoryPool(CMemoryPool &); // copy protection
void operator= (CMemoryPool &); // copy protection
void grow(); // get new chunk of memory
struct Link { Link* next; };
const unsigned esize; // size of objects to be allocated
Link* head; // list of free elements
};
void* CMemoryPool::alloc()
{
if (head == 0) grow();
Link* p = head;
head = p->next;
return p;
}
void CMemoryPool::free(void* b)
{
if (b != 0) {
Link* p = (Link*) b;
p->next = head;
head = p;
}
}
#endif /* CMEMORYPOOL_H */