为什么容器分配器需要指定它们要分配的类型?
Why do container allocators need to specify the type they're allocating?
如果我对容器使用自定义分配器,我不喜欢我必须重复包含的类型名称:
template<typename T, size_t MyAllocatorArgument>
struct MyAllocator : public std::allocator<T>
{
// ... Usual allocator implementation
};
typedef std::vector<int, MyAllocator<int, 42>> int_container;
typedef std::vector<int, MyAllocator<long, 12>> int_container_wrong_allocator;
第二行是根据标准未定义的行为,尽管大多数实现会将分配器rebind
正确的类型。
我的问题是,鉴于容器和分配器要求用于同一类型,为什么没有一些标准机制来强制执行(或完全避免它)并消除用户错误的可能性?
例如,标准可以要求使用rebind
(以有效地使分配器模板参数冗余),或者可以使用如下所示的模式,以便用户只提及包含的typename一次:
template<size_t MyAllocatorArgument>
struct MyAllocator
{
// This would be something every allocator is required to expose.
template<typename T>
struct TypedAllocator : public std::allocator<T>
{
// This is where the normal implementation of the allocator would go.
// allocate, deallocate etc.
};
};
template<typename T, typename UntypedAllocator>
struct Container
{
// All containers would do this to get the actual allocator type they would use.
typedef typename UntypedAllocator::template TypedAllocator<T> TypedAllocator;
Container() : m_allocator(TypedAllocator()) {}
void useAllocator()
{
m_allocator.allocate();
// ... or whatever else containers need to do with allocators.
}
TypedAllocator m_allocator;
};
void allocator_test()
{
// Allocated type name isn't mentioned at point of use of container;
// only once for the container. The container does all the work.
Container<int, MyAllocator<42>> c1;
}
这是一个很好的问题,您的建议是标准方案的一种可能替代方案。另一种方法是使用模板模板参数:
template<typename T>
class AnAllocator
{ ... };
template<typename T, template <typename> class Alloc = std::allocator>
class Vector
{
typedef Alloc<T> allocator_type;
...
};
Vector<int, AnAllocator> v;
分配器接口是在模板模板参数成为语言的一部分之前设计的,因此这不是一个选项。
如果今天设计分配器 API,有很多事情会有所不同,不幸的是,我们坚持使用我们拥有的API(以及尝试以半兼容方式扩展它而导致的持续复杂性)。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 不能将 "void *" 类型的值分配给类型 "TCHAR" 的实体
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 将超出范围的整数分配给有符号字符类型
- C++将一个指针分配给另一个指针时执行的类型检查
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 堆栈分配的类类型.为什么两个 ID 实例的地址相同?
- 无法将错误分配给成员函数中"类型的实体"
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- "类型名称"在 asio 分配示例中的含义
- C++指针中的这两种类型的值分配有什么区别?
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- 虚函数如何工作,分配后新的返回类型会发生什么?
- 不能分配 X 类型的对象,因为它的复制运算符隐式删除
- c++中动态分配类型的重载+操作符
- 找出函数中变量分配类型的方法