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

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值