Allocator

)Allocator

    In C++ computer programming, allocators are an important component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ability to change size during the execution of the program. To achieve this, some form of dynamic memory allocation is usually required. Allocators handle all the requests for allocation and deallocation of memory for a given container. The C++ Standard Library provides general-purpose allocators that are used by default, however, custom allocators may also be supplied by the programmer.

allocator, 即空间配置器,用于实现内存的动态分配与释放。那么为什么在vector中定义allocator而不直接使用new和delete呢?
原因便是减少开销。我们知道,new和delete申请与释放内存的开销是比较大的。如果多次new与delete会使程序的效率大大降低。这时开发者很聪明,定义了一个allocator来实现内存的管理。那它是如何减少开销的呢?
组成     功能
第一级配置器     通过malloc()与free()来申请内存的分配与释放。能模拟C++的set_new_handler()以处理内存不足的情况
第二级配置器     维护16个自由链表(free lists),负责16种小型区块的次配置能力。内存池(memory pool)以malloc()配置而得,如果内存不足,转调用第一级配置器。如果需求区块大于128bytes,就转调用第一级适配器

allocator运行原理:
当需要申请内存时,优先调用第二级配置器。若第二级配置器无法满足申请的需求,则转为调用第一级配置器。对于第二级配置器,管理着一个memory pool(内存池),每个内存池由16条自由链表构成,同一条链表上结点所占的内存大小是相同的,不同链表上结点所占的内存一般不同。当申请内存且第二级配置器能够满足时,就从链表中取出一块用于分配,也就是删除结点;当需要释放内存时,便将该内存重新插回链表,也就实现了内存的回收。

这样一来,当定义一个vector对象时,只需要动态分配一次内存和释放一次内存。对于类内内存的申请与释放,只需对指针指向操作。这样一来,也就大大减少了开销,提高了vector的效率。

下面增加几张图片,以帮助理解:(图片转载,并非原创)
Allocator1
Allocator2
Allocator3
Allocator4
Allocator5
Allocator6

// get_allocator
allocator_type get_allocator() const;

    1
    2

get_allocator:返回vector中allocator的拷贝对象

    Returns a copy of the allocator object associated with the vector.

cplusplus.com给出的例子:

// vector::get_allocator
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  int * p;
  unsigned int i;

  // allocate an array with space for 5 elements using vector's allocator:
  p = myvector.get_allocator().allocate(5);

  // construct values in-place on the array:
  for (i=0; i<5; i++) myvector.get_allocator().construct(&p[i],i);

  std::cout << "The allocated array contains:";
  for (i=0; i<5; i++) std::cout << ' ' << p[i];
  std::cout << '\n';

  // destroy and deallocate:
  for (i=0; i<5; i++) myvector.get_allocator().destroy(&p[i]);
  myvector.get_allocator().deallocate(p,5);

  return 0;
}

Output:
The allocated array contains: 0 1 2 3 4
---------------------

vector<Type> 采用默认的内存分配器
vector<Type,allocator>采用自己指定的内存分配器

vector的模板原型为
template<class T, class A = allocator<T> >
    class vector
平时我们使用vector<Type>实际上用的是allocator的默认参数值
allocator提供内存分配和管理策略,一般都用不到它
所有现在还有一些编译器不支持模板参数使用默认值,所以你得显示提供第二个参数

原文:https://blog.csdn.net/linwh8/article/details/51386430

猜你喜欢

转载自blog.csdn.net/TuxedoLinux/article/details/86590837
今日推荐