STL源码剖析 阅读(一)

1 概述

  • 六大组件:容器、算法、迭代器、仿函数、配接器(adapter)、配置器(allocator)
  • 仿函数:重载operator()

2 空间配置器 allocator

2.1 标准接口(P77)

  1. allocator(): 双层级配置器(采用哪种取决于__USE_MALLOC是否被定义)
    1.1 大于128bytes,调用第一级配置器(__malloc_alloc_template)

    • 使用malloc和free,配置失败时有相应的oom_malloc/oom_realloc,并可自定义out-of-memory handler

    1.2 小于128bytes时,采用memory pool(__default_alloc_template)

    • 维护16个free-lists(各自管理8,16,24,…,128bytes的区块)

    • free-list node

      union obj{
         union obj *free_list_link; //指向区块地址
         char client_data[1];          
         } 
    • 大于128bytes则调用第一级配置器,找到free-list中最适当的一个。如果没有可用的区块,重新填充free-list(refill),并返回区块;否则调整free-list并返回区块(从free-list移除该区块)

    • refill(size_t n) 使用chunk_alloc()取得新区块(新的n个区块为连续),n为8的整数

    • chunk_alloc(size_t n, int& nobjs) 如果剩余空间(部分/完全)满足需求则返回;否则,malloc(两倍需求量+1/16的heap_size)。如果成功设置对应的start_free/end_free/heap_size;否则,先将剩余空间给适当的free-list,然后从后面的free-list寻找未用区块并设置对应的start_free/end_free,然后递归调用chunk_alloc()返回可用区块,如果内存全用完,end_free=start_free=0,调用第一级配置器

  2. deallocate()

  • 大于128bytes则调用第一级配置器,寻找对应free_list,插入区块
  1. construct()
  2. destroy()
  • 包含两种,一种接受指针,将指针所指对象析构掉;另一种接受两个迭代器,将[first,last)间对象析构掉(只会对non trivial destructor进行析构调用)
  1. address()
  2. max_size()
  3. construct()
  4. destroy ()

2.1 内存基本处理工具

以下函数,要么全构造,要么全不构造

  1. uninitialized_copy(InputIterator first, InputIterator last, FowardIterator result)
  • Pod类型调用stl copy(),否则调用construct(char和wchar使用特化版本,使用memmove)
  1. uninitialized_fill(FowardIterator first, FowardIterator last, const T& x)
  • Pod类型调用stl fill(),否则调用construct
  1. uninitialized_fill_n(FowardIterator first, Size n, const T& x)
  • 如果FowardIterator是Pod类型(用用trivial ctor/dtor/copy/assignment),交由高阶函数fill_n()执行;否则调用construct
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章