SGI_STL空间配置器源码剖析(四)_S_refill函数

代码如下,解析已在注释中,下次再剖析_S_chunk_alloc函数和__nobjs变量的作用。

cpp 复制代码
/* Returns an object of size __n, and optionally adds to size __n free list.*/
/* We assume that __n is properly aligned. __n校准过(向上临近8)                   */
/* We hold the allocation lock.                                         */
template <bool __threads, int __inst>
void*
__default_alloc_template<__threads, __inst>::_S_refill(size_t __n)
{
    int __nobjs = 20;
    char* __chunk = _S_chunk_alloc(__n, __nobjs); // 负责分配相应大小的chunk块内存池
    _Obj* __STL_VOLATILE* __my_free_list; // 指向遍历数组下挂的链表
    _Obj* __result;
    _Obj* __current_obj;
    _Obj* __next_obj;
    int __i;

    if (1 == __nobjs) return(__chunk); // _S_chunk_alloc()引用接受nobjs,如果只生成一个chunk,直接返回
    __my_free_list = _S_free_list + _S_freelist_index(__n); // 映射数组下标,取得链表头指针

    /* Build free list in chunk */
      __result = (_Obj*)__chunk; // 记录第一个块,马上分配出去
      // 字节指针+数字,往后走n个字节。即数组中链表头指向下一个块(空闲)
      *__my_free_list = __next_obj = (_Obj*)(__chunk + __n); 
      for (__i = 1; ; __i++) {
        __current_obj = __next_obj;
        __next_obj = (_Obj*)((char*)__next_obj + __n); // next指针偏移整个块的字节n,即指向下一个块  
        if (__nobjs - 1 == __i) { // 到链表末尾了
            __current_obj -> _M_free_list_link = 0;
            break;
        } else {// 将连续的字节块真正形成链表,指针存到每个块节点的指针域里
            __current_obj -> _M_free_list_link = __next_obj;  
        }
      }
    return(__result);
}

主要就是为了将新创建的链表节点(chunk)成链。

相关推荐
bing.shao30 分钟前
golang 做AI任务执行
开发语言·人工智能·golang
源代码•宸1 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
basketball6162 小时前
python 的对象序列化
开发语言·python
fie88892 小时前
钢结构件制造车间生产调度实例:MATLAB实现(基于遗传算法)
开发语言·matlab·制造
沐知全栈开发2 小时前
PHP 安装指南
开发语言
CSDN_RTKLIB2 小时前
【字符编码】有无BOM的UTF-8
c++
Highcharts.js3 小时前
Highcharts Grid 表格/网格安装 |官方安装文档说明
开发语言·javascript·表格组件·highcharts·官方文档·安装说明·网格组件
Chary20163 小时前
opengl 学习资料路径
c++·opengl
im_AMBER3 小时前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表
Coder_Boy_3 小时前
基于SpringAI的在线考试系统-企业级软件研发工程应用规范实现细节
大数据·开发语言·人工智能·spring boot