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

相关推荐
李绍熹7 分钟前
Lua 错误处理详解
开发语言·junit·lua
I***26157 分钟前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php
灯厂码农8 分钟前
C++文件操作
开发语言·c++
️停云️24 分钟前
C++异常与智能指针
开发语言·c++
m0_4889130126 分钟前
Deep Research技术全解析:从Reasoning到Research with Reasoning的AI进化之路(值得收藏)
开发语言·人工智能·机器学习·大模型·ai大模型·大模型学习
烤麻辣烫29 分钟前
黑马程序员苍穹外卖(新手)DAY8
java·开发语言·学习·spring·intellij-idea
就叫飞六吧30 分钟前
Java 中编译一个 java 源文件产生多个 .class 文件原因
java·开发语言
IMPYLH33 分钟前
Lua 的 rawset 函数
开发语言·笔记·单元测试·lua
python零基础入门小白38 分钟前
2025年大模型面试通关秘籍!大厂高频LLMs真题全解析,一文掌握,助你轻松斩获心仪offer!
开发语言·人工智能·语言模型·架构·langchain·大模型教程·大模型面试
chenyuhao20241 小时前
MySQL事务
开发语言·数据库·c++·后端·mysql