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)成链。

相关推荐
宁瑶琴11 分钟前
COBOL语言的云计算
开发语言·后端·golang
小陈工1 小时前
2026年4月2日技术资讯洞察:数据库融合革命、端侧AI突破与脑机接口产业化
开发语言·前端·数据库·人工智能·python·安全
Zarek枫煜1 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
阿kun要赚马内1 小时前
Python中元组和列表差异:底层结构分析
开发语言·python
筱璦2 小时前
期货软件开发 - C# 调用 HQChart 指标计算 C++ 动态库
c++·microsoft·c#
不想写代码的星星2 小时前
C++ 内存管理:分区、自定义分配器、常见问题与检测工具
c++
前进的李工2 小时前
MySQL大小写规则与存储引擎详解
开发语言·数据库·sql·mysql·存储引擎
错把套路当深情3 小时前
Java 全方向开发技术栈指南
java·开发语言
前端郭德纲3 小时前
JavaScript Object.freeze() 详解
开发语言·javascript·ecmascript