您的位置:首页 >C++自定义STL分配器编写教程(代码示例)
发布于2026-03-03 阅读(0)
扫一扫,手机访问
为STL容器编写自定义分配器需实现类型定义、allocate/deallocate、construct/destroy等接口,C++17起推荐继承std::allocator或实现最小接口集,注意对齐、异常安全及is_always_equal设置。

为STL容器编写自定义分配器,核心是实现符合Allocator要求的接口:类型定义、内存分配/释放函数、对象构造/析构函数。C++17起推荐继承 std::allocator 或直接实现最小接口集,避免手动处理 rebind 等过时机制。
以下是一个线程局部缓存 + malloc/free 的简易分配器示例,支持任意类型 T:
#include <memory> #include <cstdlib> #include <new>template <typename T> 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; // 构造/析构(可选,但建议显式定义) template <typename U> constexpr SimpleAllocator(const SimpleAllocator<U>&) noexcept {} // 分配原始内存(按字节) pointer allocate(size_type n) { if (n > std::numeric_limits<size_type>::max() / sizeof(T)) throw std::bad_alloc(); if (auto p = std::malloc(n * sizeof(T))) return static_cast<pointer>(p); else throw std::bad_alloc(); } // 释放原始内存 void deallocate(pointer p, size_type) noexcept { std::free(p); } // 构造对象(placement new) template <typename U, typename... Args> void construct(U* p, Args&&... args) { ::new(static_cast<void*>(p)) U(std::forward<Args>(args)...); } // 析构对象 template <typename U> void destroy(U* p) { p->~U(); }};
// 必须提供 rebind(C++17 中仅用于模板推导,可简化为别名) template <typename T, typename U> using rebind_alloc = SimpleAllocator<U>;
将分配器作为模板参数传给容器即可。注意:分配器类型必须满足可复制性(C++17 中通常要求 is_always_equal::value == true):
#include <vector> #include <iostream>int main() { // 使用 SimpleAllocator
的 vector std::vector<int, SimpleAllocator<int>> 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)可能失效alignof(T):malloc 满足该要求;若用自定义内存池,需确保对齐(例如用 std::aligned_alloc)rebind 结构体:编译器通过 using rebind_alloc = ... 别名自动推导,或直接省略(标准库会 fallback 到模板参数推导)allocate 抛出异常,容器保证不泄露资源;deallocate 必须是 noexcept若想复用内存块,可用固定大小块池。下面仅展示核心逻辑片段(省略线程安全与碎片管理):
template <typename T>
struct 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<char*>(std::malloc(BLOCK_SIZE));
offset = 0;
}
pointer p = reinterpret_cast<pointer>(pool + offset);
offset += sizeof(T);
return p;
}
void deallocate(pointer, size_type) noexcept { /* 不立即释放,由池统一管理 */ }
template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
::new(p) U(std::forward<Args>(args)...);
}
template <typename U>
void destroy(U* p) { p->~U(); }
};
自定义分配器不是银弹——多数场景下 std::allocator 已足够高效。只有在有明确性能瓶颈(如高频小对象分配)、需内存隔离(如插件沙箱)、或调试内存问题时才值得投入。写好后务必用 std::vector<T, MyAlloc<T>> 等完整类型测试构造、析构、异常路径和迭代器稳定性。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9