您的位置:首页 > 其它

ACE内存分配器一

2007-07-28 00:21 337 查看
 ACE的内存分配器都是支持ACE_Allocator接口。

// The definition of this class is located in Malloc.cpp.

/**
* @class ACE_Allocator
*
* @brief Interface for a dynamic memory allocator that uses inheritance
* and dynamic binding to provide extensible mechanisms for
* allocating and deallocating memory.
*/
class ACE_Export ACE_Allocator

这个接口在ace/Malloc_Base.h文件中定义。

ACE提供了4个分配器,分别是

ACE_New_Allocator

ACE_Static_Allocator

ACE_Cached_Allocator

ACE_Dynamic_Cached_Allocator

这4个里面只有ACE_Cached_Allocator是强类型化的。

ACE_New_Allocator 就只是对new/delete的简单封装,具体的实现见Malloc_Allocator.h Malloc_Allocator.cpp

ACE_Static_Allocator 预先分配一个固定尺寸的内存池,然后以优化的方式从这个内存池中分配内存,分配的内存不会在被释放。

template <size_t POOL_SIZE>   //内存池的大小
class ACE_Static_Allocator : public ACE_Static_Allocator_Base
{
public:
ACE_Static_Allocator (void)
: ACE_Static_Allocator_Base (pool_, POOL_SIZE)
{
// This function <{must}> be inlined!!!
}

private:
/// Pool contents.
char pool_[POOL_SIZE];   //预先分配的内存块(池)
};

class ACE_Export ACE_Static_Allocator_Base : public ACE_Allocator
{

//char *buffer_; size_t size_;  的初始化值都是由外部传入,size_t offset_; 初始化的值为0

0 protected:
/// Don't allow direct instantiations of this class.
ACE_Static_Allocator_Base (void);

/// Pointer to the buffer.
char *buffer_; //指向pool的起始地址

/// Size of the buffer.
size_t size_;  // pool 的大小

/// Pointer to the current offset in the <buffer_>.
size_t offset_;  //pool的偏移量(已经使用的字节数)

};

//分配函数

void *
ACE_Static_Allocator_Base::malloc (size_t nbytes)
{
if (this->offset_ + nbytes > this->size_)  //判断剩余的内存是否满足所申请大小的要求
{
errno = ENOMEM;
return 0;
}
else
{
char *ptr = &this->buffer_[this->offset_];  
this->offset_ += nbytes; //增加偏移
return (void *) ptr;
}
}

可见ACE_Static_Allocator 的的内存池大小只能在编译时指定,我们可以这样实现运行时指定内存池大小

class ACE_Export Fast_Static_Allocator : public ACE_Static_Allocator_Base, public ACE_Copy_Disabled
{
public:
Fast_Static_Allocator(size_t size = 0, char* pool = NULL) :
ACE_Static_Allocator_Base ((pool == NULL && size != 0) ? new char[size] : pool, size),
delete_buffer_(pool == NULL)
{

if(this->buffer_)
{
this->offset_ = ACE_ptr_align_binary(this->buffer_, ACE_MALLOC_ALIGN) - this->buffer_;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: