貼一段內存池的代碼, 簡單, 實用. 供大家學習
namespace rpt
{
template< class T>
class TypePool
{
union Note
{
T t;
Note* next;
};
enum FreeType {
FREE_AUTO = 0,
FREE_RESERVE,
FREE_FREE,
};
public:
T* get();
void put( T* t );
void free( int i, FreeType type );
TypePool();
~TypePool();
private:
// 拒绝位拷贝和拷贝构造 sirdrm (以后可能会修改, 现在未实现)
TypePool& operator=( const TypePool<T>& p );
TypePool( const TypePool<T>& t );
HANDLE heap;
Note start;
Note end;
Note temp;
BOOL bCreateSucceeded;
};
template<class T>
T* TypePool<T>::get ()
{
if( start.next == &end )
{
return (T*)::HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(Note) );
} else {
temp.next = start.next;
start.next = temp.next->next;
return (T*)temp.next;
}
}
template<class T>
void TypePool<T>::put ( T* t )
{
((Note*)t)->next = start.next;
start.next = ((Note*)t);
}
template<class T>
void TypePool<T>::free ( int i, FreeType type )
{
// sirdrm 未实现
}
template<class T>
TypePool<T>::TypePool( const TypePool<T>& t )
{
// sirdrm 未实现
}
template<class T>
TypePool<T>::TypePool()
{
heap = NULL;
bCreateSucceeded = FALSE;
heap = ::HeapCreate( 0, 4096, 0 );
if( heap != NULL)
{
bCreateSucceeded = TRUE;
}
start.next = &end;
end.next = NULL;
}
//// 拒绝位拷贝
template<class T>
TypePool<T>& TypePool<T> :: operator= (const TypePool<T> & p )
{
}
template<class T>
TypePool<T> :: ~TypePool()
{
if( heap != NULL )
{
::HeapDestroy ( heap );
}
}
}