C++: STL内存分配器--allocator

本文介绍了C++ STL中的内存分配器,包括其作用、默认分配器以及GNU STL提供的几种特殊分配器如__pool_alloc、__mt_alloc、array_allocator和malloc_allocator。STL allocator允许分离内存分配和对象构造,提高性能和内存管理灵活性。标准容器默认使用std::allocator,而自定义allocator只需实现allocate和deallocate方法。
摘要由CSDN通过智能技术生成

STL内存分配器--allocator


一、STL内存分配器

分配器(allocator))是C ++标准库的一个组件, 主要用来处理所有给定容器(vector,list,map等)内存的分配和释放。C ++标准库提供了默认使用的通用分配器std::allocator,但开发者可以自定义分配器。
GNU STL除了提供默认分配器,还提供了__pool_alloc、__mt_alloc、array_allocator、malloc_allocator 内存分配器。
__pool_alloc :SGI内存池分配器
__mt_alloc : 多线程内存池分配器
array_allocator : 全局内存分配,只分配不释放,交给系统来释放
malloc_allocator :堆std::malloc和std::free进行的封装

二、STL allocator

1、STL allocator简介
new会分配内存并执行对象构造函数,delete会执行对象析构函数并释放内存。如果将内存分配和对象构造分离,可以先分配大块内存,只在需要时才真正执行对象构造函数。
STL在头文件memory中提供了一个allocator类,允许将分配和对象构造分离,提供更好的性能和更灵活的内存管理能力。为了定义一个allocator对象,必须指明allocator可以分配的对象类型。当allocator分配内存时,会根据给定的对象类型来确定恰当的内存大小和对齐位置。

  template<typename _Tp>
    class allocator : public __allocator_base<_Tp>
    {
   
   public:
      typedef size_t     size_type;
      typedef ptrdiff_t  difference_type;
      typedef _Tp*       pointer;
      typedef const _Tp* const_pointer;
      typedef _Tp&       reference;
      typedef const _Tp& const_reference;
      typedef _Tp        value_type;

      template<typename _Tp1>
	struct rebind
	{
    typedef allocator<_Tp1> other; };


      allocator() throw() {
    }

      allocator(const allocator& __a) throw()
      : __allocator_base<_Tp>(__a) {
    }

      template<typename _Tp1>
	allocator(const allocator<_Tp1>&) throw() {
    }

      ~allocator() throw() {
    }

      // Inherit everything else.
    };

根据C++标准规范,STL中分配器的对外接口、成员变量都一样,只是接口内部实现有区别。
allocator实现在模板类new_allocator中:

  template<typename _Tp>
    class new_allocator
    {
   
    public:
      typedef size_t     size_type;
      typedef ptrdiff_t  difference_type;
      typedef _Tp*       pointer;
      typedef const _Tp* const_pointer;
      typedef _Tp&       reference;
      typedef const _Tp& const_reference;
      typedef _Tp        value_type;

      template<typename _Tp1>
	struct rebind
	{
    typedef new_allocator<_Tp1> other; };

      new_allocator() _GLIBCXX_USE_NOEXCEPT {
    }

      new_allocator(const new_allocator&) _GLIBCXX_USE_NOEXCEPT {
    }

      template<typename _Tp1>
	  new_allocator(const new_allocator<_Tp1>&) _GLIBCXX_USE_NOEXCEPT 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值