核心概述
线性分配器的 STL 封装以标准分配器接口对接各类容器,在 O(1) 分配与一次性释放的前提下降低频繁分配释放的开销。
原文引述
Description: STL-compatible allocator that uses a linear (bump-pointer) pool. Provides rebind, construct/destroy, and propagates on copy/move. Works with all standard containers. ——来源:本节点英文注释 Time: Same as LinearAllocator: O(1) per allocation; O(1) bulk deallocation ——来源:本节点英文注释 Status: tested ——来源:本节点英文注释
展开阐述
-
模板接口(据实现)
- template<class T, size_t N> struct LinearAllocatorSTL {
- using value_type = T;
- using pointer = T*;
- using size_type = size_t;
- template
struct rebind { using other = LinearAllocatorSTL<U,N>; }; - LinearAllocatorSTL() noexcept;
- template
LinearAllocatorSTL(const LinearAllocatorSTL<U,N>&) noexcept; - pointer allocate(size_type n);
- void deallocate(pointer p, size_type n) noexcept {}
- template<class U, class… Args> void construct(U* p, Args&&… args);
- template
void destroy(U* p); }
- 重载 operator==/!= 以支持不同类型间相等性。
- template<class T, size_t N> struct LinearAllocatorSTL {
-
核心要点
- 与标准分配器接口兼容,可作容器模板参数。
- allocate 使用底层线性池(见 127-杂项-线性分配器)分配。
- deallocate 空实现,依赖整体释放(析构时或手动 reset)。
- construct/destroy 调用 placement new 与显式析构。
- rebind 使容器能申请其他类型的内存(如 node-based containers)。
-
使用示例
- using Alloc = LinearAllocatorSTL<int, 1000000>;
- std::vector<int, Alloc> vec;
- vec.reserve(1000); // 快速从池分配
- // 使用 vec…
- // 析构时整个池释放,或手动调用 pool.reset()。
-
优势
- 向量等容器扩容时,避免多次系统调用。
- node-based 容器(list、map、set)分配节点时性能提升明显。
- 临时容器(算法内)可快速分配与整体释放。
-
局限
- 容器析构前需确保无悬挂引用。
- 不能跨线程共享同一池(除非加锁)。
- 大对象或长生命周期对象仍建议常规分配器。
-
与自定义内存池关系
- 可作为更复杂内存池(分段池、对象池)的基础。
- 常用于竞赛/嵌入式环境,减少内存碎片。