为STL容器编写自定义分配器需实现类型定义、allocate/deallocate、construct/destroy等接口,C++17起推荐继承std::allocator或实现最小接口集,注意对齐、异常安全及is_always_equal设置。

为STL容器编写自定义分配器,核心是实现符合Allocator要求的接口:类型定义、内存分配/释放函数、对象构造/析构函数。C++17起推荐继承 std::allocator 或直接实现最小接口集,避免手动处理 rebind 等过时机制。
基础自定义分配器(C++17风格)
以下是一个线程局部缓存 + malloc/free 的简易分配器示例,支持任意类型 T:
#include#include #include template
struct SimpleAllocator { using value_type = T; using pointer = T; using const_pointer = const T; using reference = T&; using const_reference = const T&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; // C++17 要求:提供 is_always_equal(若不依赖状态,设为 true) using is_always_equal = std::true_type; // 构造/析构(可选,但建议显式定义) templateconstexpr SimpleAllocator(const SimpleAllocator&) noexcept {} // 分配原始内存(按字节) pointer allocate(size_type n) { if (n > std::numeric_limits ::max() / sizeof(T)) throw std::bad_alloc(); if (auto p = std::malloc(n * sizeof(T))) return static_cast (p); else throw std::bad_alloc(); } // 释放原始内存 void deallocate(pointer p, size_type) noexcept { std::free(p); } // 构造对象(placement new) template void construct(U* p, Args&&... args) { ::new(static_cast (p)) U(std::forward (args)...); } // 析构对象 template void destroy(U* p) { p->~U(); } };
立即学习“C++免费学习笔记(深入)”;
// 必须提供 rebind(C++17 中仅用于模板推导,可简化为别名) template
using rebind_alloc = SimpleAllocator; 使用自定义分配器实例化容器
将分配器作为模板参数传给容器即可。注意:分配器类型必须满足可复制性(C++17 中通常要求
is_always_equal::value == true):#include#include int main() { // 使用 SimpleAllocator
的 vector std::vector > vec; vec.push_back(42); vec.push_back(100); for (int x : vec) { std::cout << x << " "; // 输出:42 100 } return 0;}
关键注意事项
- 不要在分配器中保存状态(除非明确需要):若需状态(如内存池句柄),必须定义
is_always_equal = std::false_type,并实现拷贝/移动语义,且容器操作(如swap)可能失效- allocate 返回的指针必须对齐到
alignof(T):malloc满足该要求;若用自定义内存池,需确保对齐(例如用std::aligned_alloc)- C++17 后无需手写
rebind结构体:编译器通过using rebind_alloc = ...别名自动推导,或直接省略(标准库会 fallback 到模板参数推导)- 异常安全:若
allocate抛出异常,容器保证不泄露资源;deallocate必须是noexcept进阶:带内存池的分配器(简版示意)
若想复用内存块,可用固定大小块池。下面仅展示核心逻辑片段(省略线程安全与碎片管理):
templatestruct PoolAllocator { using value_type = T; using pointer = T*; using is_always_equal = std::true_type; private: static constexpr size_t BLOCK_SIZE = 4096; static inline char* pool = nullptr; static inline size_t offset = 0;
public: pointer allocate(size_type n) { if (n != 1) throw std::bad_alloc(); // 仅支持单对象(简化) if (!pool || offset + sizeof(T) > BLOCK_SIZE) { pool = static_cast
(std::malloc(BLOCK_SIZE)); offset = 0; } pointer p = reinterpret_cast (pool + offset); offset += sizeof(T); return p; } void deallocate(pointer, size_type) noexcept { /* 不立即释放,由池统一管理 */ } templatevoid construct(U* p, Args&&... args) { ::new(p) U(std::forward (args)...); } template void destroy(U* p) { p->~U(); } };
自定义分配器不是银弹——多数场景下
std::allocator已足够高效。只有在有明确性能瓶颈(如高频小对象分配)、需内存隔离(如插件沙箱)、或调试内存问题时才值得投入。写好后务必用std::vector等完整类型测试构造、析构、异常路径和迭代器稳定性。>










