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

相关推荐
沐怡旸3 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4167 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥9 小时前
C++ std::set
c++
侃侃_天下10 小时前
最终的信号类
开发语言·c++·算法
博笙困了10 小时前
AcWing学习——差分
c++·算法
echoarts10 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix10 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁10 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁10 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥11 小时前
C++ std::vector
c++