商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++自定义STL分配器编写教程(代码示例)

C++自定义STL分配器编写教程(代码示例)

  发布于2026-03-03 阅读(0)

扫一扫,手机访问

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

C++如何为STL容器编写自定义分配器(Allocator)?(代码示例)

为STL容器编写自定义分配器,核心是实现符合Allocator要求的接口:类型定义、内存分配/释放函数、对象构造/析构函数。C++17起推荐继承 std::allocator 或直接实现最小接口集,避免手动处理 rebind 等过时机制。

基础自定义分配器(C++17风格)

以下是一个线程局部缓存 + 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 &lt;typename U&gt;
constexpr SimpleAllocator(const SimpleAllocator&lt;U&gt;&amp;) noexcept {}

// 分配原始内存(按字节)
pointer allocate(size_type n) {
    if (n &gt; std::numeric_limits&lt;size_type&gt;::max() / sizeof(T))
        throw std::bad_alloc();
    if (auto p = std::malloc(n * sizeof(T)))
        return static_cast&lt;pointer&gt;(p);
    else
        throw std::bad_alloc();
}

// 释放原始内存
void deallocate(pointer p, size_type) noexcept {
    std::free(p);
}

// 构造对象(placement new)
template &lt;typename U, typename... Args&gt;
void construct(U* p, Args&amp;&amp;... args) {
    ::new(static_cast&lt;void*&gt;(p)) U(std::forward&lt;Args&gt;(args)...);
}

// 析构对象
template &lt;typename U&gt;
void destroy(U* p) {
    p-&gt;~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 &lt;&lt; x &lt;&lt; " "; // 输出: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

进阶:带内存池的分配器(简版示意)

若想复用内存块,可用固定大小块池。下面仅展示核心逻辑片段(省略线程安全与碎片管理):

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 &lt;typename U, typename... Args&gt;
void construct(U* p, Args&amp;&amp;... args) {
    ::new(p) U(std::forward&lt;Args&gt;(args)...);
}

template &lt;typename U&gt;
void destroy(U* p) { p-&gt;~U(); }

};

自定义分配器不是银弹——多数场景下 std::allocator 已足够高效。只有在有明确性能瓶颈(如高频小对象分配)、需内存隔离(如插件沙箱)、或调试内存问题时才值得投入。写好后务必用 std::vector<T, MyAlloc<T>> 等完整类型测试构造、析构、异常路径和迭代器稳定性。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注