【发布时间】:2016-01-01 22:19:09
【问题描述】:
给定一个非无状态自定义分配器A(例如,arena 分配器,绑定到一些运行时已知大小的连续内存块)和类S,包含AllocatorAwareContainer 类型的文件:
struct S
{
A() = default;
// another c-tors
std::vector< T > v;
std::shared_ptr< U > s;
};
我想将A 用于S 类的子集(甚至所有)AllocatorAwareContainer 字段。很明显,我应该为S类提供另一个模板参数,并相应地更改所有感兴趣的数据成员的类型,如下所示:
template< typename A = std::allocator< void > >
struct S
{
// c-tors
template< typename X >
using allocator = typename std::allocator_traits< A >::template rebind< X >::other;
std::vector< T, allocator< T > > v;
std::shared_ptr< U, allocator< U > > s;
};
我应该对现有构造函数和其他构造函数进行哪些更改(假设 A 不是 DefaultConstructible 并且可能存在任何其他可能的限制)?
我应该将分配器A 存储在S 类的附加字段中吗?
为类使用自定义分配器的一般技巧是什么?
【问题讨论】:
标签: c++ memory-management stl c++14 allocator