文档介绍:踏雪无痕
SGI STL 内存池(转)
分类: C++ 2012-07-20 11:20 131人阅读评论(0) 收藏举报
将SGI STL的内存池抠了出来,win32平台
//
#ifndef mem_pool_h
#define mem_pool_h
#pragma once
#define ALIGN     512
#define MAX_BLOCK_SIZE   20 * 1024
#define BLOCK_LIST_NUM   MAX_BLOCK_SIZE / ALIGN
class mem_pool
{
CRITICAL_SECTION alloc_lock;
union obj{
union obj* free_list_link;
char client_data[1];
};
obj* free_list [BLOCK_LIST_NUM];
static inline size_t round_up(size_t bytes){
return (bytes + ALIGN - 1) & ~(ALIGN - 1);
}
static inline size_t free_list_index(size_t bytes){
return (bytes + ALIGN - 1) / ALIGN - 1;
}
char* start_free;
char* end_free;
size_t heap_size;
char* chunk_alloc(size_t size, int& nobjs);
void* refill(size_t n);
public:
mem_pool(void);
~mem_pool(void);
void* allocate(size_t n);
void deallocate(void* p, size_t n);
inline size_t mem_size(){return heap_size;}
};
#endif
// : 定义控制台应用程序的入口点。
//
#include ""
#include ""
mem_pool::mem_pool(void){
InitializeCriticalSection(&alloc_lock);
heap_size = 0;
start_free = 0;
end_free = 0;
memset(free_list, 0, sizeof(free_list));
}
mem_pool::~mem_pool(void){
1
mem_pool::~mem_pool(void){
DeleteCriticalSection(&alloc_lock);
}
char* mem_pool::chunk_alloc(size_t size, int& nobjs){
char* result;
size_t total_bytes = size * nobjs;
size_t bytes_left = end_free - start_f