标签:空间配置器
__malloc_alloc_template分配器:该分配器是对malloc、realloc以及free的封装:
当调用malloc和realloc申请不到内存空间的时候,会改调用oom_malloc()和oom_realloc(),这两个函数会反复调用用户传递过来的out of memory handler处理函数,直到能用malloc或者realloc申请到内存为止。
如果用户没有传递__malloc_alloc_oom_handler,__malloc_alloc_template会抛出__THROW_BAD_ALLOC异常。所以,内存不足的处理任务就交给类客户去完成。
//
#include<iostream>
#include<new>
using namespace std;
template <int inst>
class MallocAllocTemplate
{
public:
typedef void(*MallocAllocHandler)();
protected:
static MallocAllocHandler _handler;
static void* Oom_Malloc(size_t n)
{
MallocAllocHandler handler = NULL;
void* ret = NULL;
while (1)
{
handler = _handler;
if (handler == NULL)
{
cout << "out of memory" << endl;
//exit(1);
}
(*handler)();
ret = malloc(n);
if (ret)
return ret;
}
}
public:
static void * Allocate(size_t n)
{
void *result = malloc(n);
if (0 == result) result = Oom_Malloc(n);
return result;
}
static void Deallocate(void *p, size_t)
{
free(p);
}
static void(*SetMallocHandler(MallocAllocHandler f))()
{
void(*old)() = _handler;
_handler = f;
return(old);
}
};
void(*MallocAllocTemplate<1>::_handler)() = 0;
void Test1()
{
MallocAllocTemplate<1> d;
//int *p=(int*)MallocAllocTemplate<1>::Allocate(sizeof(int));
int *p=(int*)d.Allocate(sizeof(int));
*p = 2;
cout << *p << endl;
d.Deallocate(p, sizeof(int));
}__default_alloc_template分配器
这个分配器采用了内存池的思想,有效地避免了内碎片的问题(顺便一句话介绍一下内碎片和外碎片:内碎片是已被分配出去但是用不到的内存空间,外碎片是由于大小太小而无法分配出去的空闲块)。
如果申请的内存块大于128bytes,就将申请的操作移交__malloc_alloc_template分配器去处理;如果申请的区块大小小于128bytes时,就从本分配器维护的内存池中分配内存。
分配器用空闲链表的方式维护内存池中的空闲空间
本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1831719
标签:空间配置器
原文地址:http://10541556.blog.51cto.com/10531556/1831719