山寨STL实现之allocator
作为一个山寨的STL,那么不得不提的是其中的allocator(空间配置器)。顾名思义,它是负责空间分配用的,下面代码十分简单,仅对C函数malloc和free进行了薄薄的一层封装,同时给定了自定义函数free_handler用于在空间分配时候由于内存被占满了而导致的分配失败。
这里值得注意的是:这个释放函数的函数指针应该是由调用方来负责指定,并且它仅有一个参数表明至少需要释放多少字节的内存。
下面来看代码,代码非常简单,应此这里就不逐一展开说明了。
template <typename T>
class allocator
{
public:
allocator()
{
}
allocator(const allocator<T>&)
{
}
static T* allocate()
{
const size_t size = sizeof(T);
T* result = (T*)malloc(size);
while(result == 0)
{
if(free_handler) free_handler(size);
else __THROW_BAD_ALLOC;
result = (T*)malloc(size);
}
return result;
}
static T* allocate(size_t n)
{
const size_t size = n * sizeof(T);
if(size <= 0) throw "bad allocate size";
T* result = (T*)malloc(size);
while(result == 0)
{
if(free_handler) free_handler(size);
else __THROW_BAD_ALLOC;
result = (T*)malloc(size);
}
return result;
}
static void deallocate(T* p)
{
free(p);
}
static void deallocate(T* p, size_t)
{
free(p);
}
static T* reallocate(T* p, size_t old_size, size_t n)
{
const size_t size = n * sizeof(T);
if(size <= 0) throw "bad reallocate size";
T* result = (T*)realloc(p, size);
while(result == 0)
{
if(free_handler) free_handler(size);
else __THROW_BAD_ALLOC;
result = (T*)realloc(p, size);
}
return result;
}
public:
static void(*free_handler)(size_t);
static void set_handler(void(*h)(size_t))
{
free_handler = h;
}
};
template <typename T>
typename void (*allocator<T>::free_handler)(size_t) = 0;
完整代码请到http://qlanguage.codeplex.com/下载

浙公网安备 33010602011771号