C++嵌套容器自定义分配器:如何用静态缓冲区初始化外层vector
自定义静态缓冲区分配器开发进展
目前已完成std::list、std::vector、std::basic_string等标准简单容器的适配,核心实现了无动态内存开销的静态缓冲区分配器,核心逻辑简洁直接,代码如下:
#include <memory> template <typename T> class StaticBufferAlloc : std::allocator<T> { private: T *memory_ptr; std::size_t memory_size; public: typedef std::size_t size_type; typedef T *pointer; typedef T value_type; StaticBufferAlloc(T *memory_ptr, size_type memory_size) : memory_ptr(memory_ptr), memory_size(memory_size) {} StaticBufferAlloc(const StaticBufferAlloc &other) throw() : memory_ptr(other.memory_ptr), memory_size(other.memory_size){}; pointer allocate(size_type n, const void *hint = 0) { return memory_ptr; } // 直接返回静态缓冲区地址 void deallocate(T *ptr, size_type n) {} // 静态缓冲区由创建者负责回收,无需分配器处理 size_type max_size() const { return memory_size; } };
单容器场景验证状态
当前单容器使用方式运行完全正常,当插入元素数超出缓冲区最大容量时会按设计抛出异常,符合预期,验证代码如下:
using inner = std::vector<int, StaticBufferAlloc<int>>; int buffer[201]; auto alloc1 = StaticBufferAlloc<int>(&buffer[100], 50); inner v1(0, alloc1); assert(v1.size() == 0); const int N = 10; // 连续插入10个整数 for (size_t i = 0; i < N; i++) { v1.push_back(i); } assert(v1.size() == N);
嵌套容器适配需求
目前需要实现vector嵌套vector的矩阵结构,核心要求是:外层容器、所有作为元素的内层容器,全部共享同一块静态缓冲区完成内存分配。
初步尝试使用std::scoped_allocator_adaptor实现适配,目前已编写的相关代码片段如下:
using inner = std::vector<int, StaticBufferAlloc<int>>; using outer = std::vector<inner, std::scoped_allocator_adaptor<StaticBufferAlloc<inner>>>; int buffer[201]; auto alloc1 = StaticBufferAlloc<int>(&buffer[100], 50); auto alloc2 = StaticBufferAlloc<int>(&buffer[150], 50); inner v1(0, alloc1); inner v2(0, alloc2); assert(v1.size() == 0); assert(v2.size() == 0); const int N = 10; // 连续插入10个整数 for (size_t i = 0; i < N; i++) { v1.push_back(i); v2.push_back(i); } assert(v1.size() == N); assert(v2.size() == N); outer v // 此处未完成外层vector的构造逻辑 v.push_back(v1); v.push_back(v2);
外层vector的构造实现方法
当前核心需要解决的问题是:构造外层vector时,如何传入绑定了对应静态缓冲区的分配器实例。
结合std::scoped_allocator_adaptor的设计逻辑,正确的构造流程如下:
- 先创建绑定整块静态缓冲区的基础分配器实例,无需为不同内层容器拆分独立的分配器对象
- 将基础分配器实例用
std::scoped_allocator_adaptor包裹,作为构造参数传入外层vector的构造函数 - 外层vector初始化完成后,在插入、构造内层元素时,
std::scoped_allocator_adaptor会自动将同一个分配器实例传递给内层容器的构造函数,最终实现全层级容器共享同一块静态缓冲区的目标
对应正确构造示例代码:
using inner = std::vector<int, StaticBufferAlloc<int>>; // 定义外层容器的分配器类型:由基础静态分配器经scoped适配 using outer_alloc = std::scoped_allocator_adaptor<StaticBufferAlloc<inner>>; using outer = std::vector<inner, outer_alloc>; int buffer[201]; // 初始化绑定整块静态缓冲区的基础分配器 auto base_alloc = StaticBufferAlloc<inner>( reinterpret_cast<inner*>(buffer), sizeof(buffer) / sizeof(inner) ); // 构造外层vector,传入适配后的分配器实例 outer v(base_alloc);
注意:现有分配器的
allocate实现直接返回固定的缓冲区起始地址,没有记录已分配的偏移位置,在嵌套场景下多个层级同时申请内存时会出现地址重复、内存冲突的问题。需要在分配器内新增已分配偏移量的成员变量,每次执行allocate时根据申请的元素大小计算目标地址、更新内部偏移计数,才能实现真正的共享缓冲区效果。
内容的提问来源于stack exchange,提问作者Oussama Ben Ghorbel
相关产品推荐
相关产品推荐

