分类: C/C++
2010-03-11 18:06:55
所有ACE容器都要求分配器支持ACE_Allocator接口,它是一个真正的C++接口,所有的方法都是纯虚函数.ACE提供了若干分配器实现:
(1)、ACE_New_Allocator:使用new操作符直接从堆中分配内存;
(2)、ACE_Static_Allocator:预分配一个固定尺寸的内存池,然后以优化的方式从这个内存池中分配内存;内存永不释放;
(3)、ACE_Cached_Allocator:固定尺寸的强类型化的分配器,它会分配一些强类型化的、尺寸固定的内存块,块的数量很明确,这些块在分配时返回给请求者,在释放时返回到自由列表中;
(4)、ACE_Dynamic_Cached_Allocator:缓存分配器的一种版本,它允许你在运行时而不是在编译时指定缓存块的尺寸和数量.与ACE_Cached_Allocator不同,这些块不是强类型化的;
分配器的通用接口ACE_Malloc:
除了ACE_Allocator之外,ACE还有一个名为ACE_Malloc的通用接口.这个分配器的功能比ACE_Allocator强大得多,允许你使用像System V共享内存或内存映射文件这样的技术分配内存.如果你想要使用这些技术分配你的容器,你可以使用适配器ACE_Allocator_Adapter,把ACE_Malloc模板类适配为ACE_Allocator接口;
例子代码:
int TestContainers::testAllocator(void)
{
ACE_DEBUG( (LM_INFO, ACE_TEXT("----------> use ACE_Allocator <----------\n")) );
int nReturn = 0, i = 0;
ACE_Allocator* allocator = NULL;
size_t block_size = 0;
//malloc a allocator
block_size = sizeof(ACE_Node
ACE_NEW_RETURN(allocator, ACE_Dynamic_Cached_Allocator
ACE_DEBUG( (LM_INFO, ACE_TEXT("Number of active objects: %d\n"), DataElement::numOfActiveObjects()) );
ACE_Unbounded_Stack
ACE_DEBUG( (LM_INFO, ACE_TEXT("push ten elements into ustack ...\n")) );
for(i = 1; i <= 10; i++)
{
DataElement elem(i);
nReturn = ustack.push(elem);
if(nReturn == -1)
{
ACE_DEBUG( (LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("push next element")) );
}
else
{
ACE_DEBUG( (LM_ERROR, ACE_TEXT("push %d ok[%d]\n"), elem.getData(), nReturn) );
}
}
//malloc one block memory from allocator
ACE_DEBUG( (LM_INFO, ACE_TEXT("malloc one block memory from allocator...\n")) );
void* furtherMemory = NULL;
furtherMemory = allocator->malloc(block_size);
ACE_ASSERT( furtherMemory == NULL);
ACE_DEBUG( (LM_ERROR, ACE_TEXT("---> %p\n"), ACE_TEXT("No Memory")) );
//free some elements in the ustack
ACE_DEBUG( (LM_INFO, ACE_TEXT("free some elements in the ustack ...\n")) );
DataElement d;
for(i = 1; i <= 3; i++)
{
ustack.pop(d);
}
ACE_DEBUG( (LM_INFO, ACE_TEXT("dddddddddddd\n")) );
//malloc one block memory from allocator against
furtherMemory = NULL;
furtherMemory = allocator->malloc(block_size);
ACE_ASSERT( furtherMemory != NULL);
ACE_DEBUG( (LM_INFO, ACE_TEXT("malloc one block memory from allocator ok\n")) );
return 0;
};