ACE内存分配器一

 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_;
  }
 }

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值