第26.19章:分配器

English

1. 分配器是类型的一部分

fast_io 容器把分配器作为模板参数。没有全局分配器开关, 也没有悄悄退回 malloc:


::fast_io::containers::vector<int, ::fast_io::native_global_allocator> v;

便利别名 ::fast_io::vector<T> 就是填入 native_global_allocator 的同一个容器。 Freestanding 目标显式写分配器,并选择自己的策略。

2. 标准分配器

名字 角色 模块
native_global_allocator 平台默认:c_malloc、NT 堆、Win32 堆、mimalloc 或 freestanding 分配器, 取决于构建。 fast_io
native_typed_global_allocator<T> 全局分配器的类型化视图。 fast_io
native_thread_local_allocator 线程局部分配器;未覆盖时默认是全局分配器。 fast_io
native_typed_thread_local_allocator<T> 线程局部分配器的类型化视图。 fast_io
generic_allocator_adapter<A> 把原始分配器变成容器接口。 fast_io
typed_generic_allocator_adapter<A, T> 套在另一个适配器外面的类型化适配器。 fast_io
freestanding_global_allocator fast_io 声明,目标定义。 头文件侧

平台特定分配器由构建选择: c_malloc_allocator、nt_rtlallocateheap_allocator、 win32_heapalloc_allocator、wincrt_malloc_dbg_allocator、 linux_kmalloc_allocator 和 mimalloc_allocator。

3. 适配器 Flags

allocator_adapter_flags 控制失败和安全策略:

Flag 效果
none默认:分配失败和越界快速失败。
secure_clear释放前擦除内存。
throws_on_allocation_failure分配失败通过 herbception 报告,而不是终止。
throws_on_violations容器越界通过 herbception 报告。
throws_on_overflow大小溢出通过 herbception 报告。
prefer_big_allocation_on_stack大临时分配优先用栈空间。

Flags 可以按位或。策略是分配器类型的一部分, 所以容器的失败行为是编译期属性,不是全局设置。

4. 分配结果

底层契约返回 allocation_least_result:指针加可用数量。 “least” 表示分配器可以返回多于请求的数量。自定义分配器实现它支持的操作; 适配器分派到 _die 或 _try 形式。

操作形状 含义
allocate_*分配,不清零。
allocate_zero_*分配并清零。
allocate_aligned_*按请求对齐分配。
allocate_aligned_conditional_zero_at_least_* 通用形式:对齐、大小和清零标志。
reallocate_*扩大/缩小已有块。
deallocate_*释放块。

_die 变体失败时终止。_try 变体通过 herbception 通道报告 std::errc::not_enough_memory。适配器在两者之间转换: die 模式下,只提供 try 的分配器错误会被捕获并终止程序; try 模式下,只提供 die 的分配器是编译期错误。

5. 编写自定义分配器

实现目标需要的最小集合,然后包一层:


class my_arena
{
public:
    static ::fast_io::allocation_least_result
    allocate_aligned_conditional_zero_at_least_die(
        ::std::size_t alignment, ::std::size_t n, bool) noexcept;

    static void deallocate_aligned_n(
        void *p, ::std::size_t alignment, ::std::size_t n) noexcept;
};

using arena_alloc = ::fast_io::generic_allocator_adapter<my_arena>;
::fast_io::containers::vector<int, arena_alloc> v;

适配器通过调用通用形式补齐缺失的便利操作。分配器有 handle 或状态时, 用 typed_generic_allocator_adapter 或状态适配器。

6. 选择分配器

场景 使用
普通 hosted 代码native_global_allocator
每线程 scratchnative_thread_local_allocator
内核或嵌入式 arena自定义分配器 + generic_allocator_adapter
秘密和密钥材料带 secure_clear 的分配器
可恢复的分配失败带 throws_on_allocation_failure 的分配器
带边界检查的容器带 throws_on_violations 的分配器

7. 模块与头文件边界

fast_io 模块导出 generic_allocator_adapter、 typed_generic_allocator_adapter、native_global_allocator、 native_typed_global_allocator、native_thread_local_allocator 和 native_typed_thread_local_allocator,以及构建选中的平台分配器。 freestanding_global_allocator、allocation_least_result 和 allocator_adapter_flags 目前在头文件侧。

分配器不匹配是类型错误。 用一个分配器实例化的容器不能赋给另一个 分配器的容器。这是刻意的:失败策略和内存来源随类型走。

要点