/* $Id: pool.hpp,v 1.5 2005/08/31 15:37:58 uwe Exp $ */ #ifndef _POOL_HPP_ #define _POOL_HPP_ /**********************************************************/ #include "pvector_t.hpp" #include /**********************************************************/ #define POOL_GRANULARITY POINTER_VECTOR_GRANULARITY /**********************************************************/ //! a pool for certain data types /*! This class allows to administrate objects of the template * parameter type T in a pool. This means that the objects are kept * in a pool after they are not used any more. If a new object of * this type is needed, it is taken from the pool of currently unused * objects. If this part of the pool is empty, the pool of currently * unused object is enlarged first. The pool of unused objects is * \b never diminuished! * \br * So, if you use this class, do never call "new" or "delete", but * Pool::newItem() or Pool::removeItem() instead. */ template class Pool { public: //! constructor Pool() : m_numUsed(0) {} //! destructor ~Pool() { reset(); } //! returns the number of currently used items Sint32 getNumUsedItems() const { return m_numUsed; } //! returns the total number of items in the pool Sint32 getPoolSize() const { return m_items.getSize() * POOL_GRANULARITY; } //! get an unused item from the pool T* newItem() { if( m_numUsed >= m_access.getSize() ) { T *newBlock = NEW T [POOL_GRANULARITY]; m_items.append( newBlock ); for( Sint32 i = 0; i < POOL_GRANULARITY; i++ ) { m_access.append( newBlock + i ); } } return m_access[m_numUsed++]; } //! remove the passed item from the used items void removeItem( const T* item ) { for( Sint32 i = 0; i < m_numUsed; i++ ) { if( m_access[i] == item ) { m_access[i] = m_access[--m_numUsed]; m_access[m_numUsed] = (T*)item; } } } //! move all currently used objects to the pool of unused ones void removeAllItems() { while( getNumUsedItems() > 0 ) { removeItem( m_access[0] ); } } /*! \brief resets the class to the state after creation. * Note that this is the \b only way to really \c delete an * object and release some memory. */ void reset() { while( m_access.getSize() > 0 ) { m_access.swap_unhook( 0 ); } while( m_items.getSize() > 0 ) { delete [] m_items.swap_unhook( 0 ); } m_access.reset(); m_items.reset(); m_numUsed = 0; } protected: Sint32 m_numUsed; //!< number of currently used items PointerVector m_access; //!< PointerVector m_items; //!< pool of objects }; /**********************************************************/ #endif // _POOL_HPP_