std::vector<int, std::allocator<char>>是否有效?

4
标准并未涉及到std::vector的分配器,只要求分配器满足Allocator概念。没有关于分配器的value_type、reference_type等任何说明。
我认为std::vector<T, A>会将A内部重新绑定为一个用于T的分配器,因此我给了一个使用std::allocator<char>的向量,并且它按预期工作。
但是,如果给出std::allocator<void>,GCC会生成错误,如下所示:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/include/g++-v4/ext/alloc_traits.h: In instantiation of ‘struct __gnu_cxx::__alloc_traits<std::allocator<void> >’:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/include/g++-v4/bits/stl_vector.h:75:28:   required from ‘struct std::_Vector_base<int, std::allocator<void> >’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/include/g++-v4/bits/stl_vector.h:214:11:   required from ‘class std::vector<int, std::allocator<void> >’
a.cpp:5:42:   required from here
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/include/g++-v4/ext/alloc_traits.h:109:53: error: forming reference to void
     typedef value_type&                             reference;
                                                 ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/include/g++-v4/ext/alloc_traits.h:110:53: error: forming reference to void
     typedef const value_type&                       const_reference;
                                                 ^

这是GCC的一个bug吗?还是我对标准的理解有误?

  • GCC版本:4.9.2

即使在实现中,分配器的value_type不需要与向量元素类型匹配,您仍然必须传递有效的分配器。std::allocator<void>是无效的,因为模板参数需要是“非const对象类型”,而void不是。 - Ben Voigt
@BenVoigt 对于 voidstd::allocator 存在一个明确的特化。 - T.C.
@T.C.:对的,但它是一个分配器工厂,而不是分配器。allocator_traits在使用allocator<void>时失败了。 - Ben Voigt
libstdc++故意支持std::vector<int,std::allocator<char>>(https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64865#c3),因此我想知道在`allocator<void>`上中断是否是一个疏忽。 - T.C.
1个回答

7
不可以。表格99的第一行不允许这样做:

为什么容器不能通过重新绑定来定义allocator_type - dyp
1
在理论上是可以的。但标准将allocator_type typedef定义为单个容器的Allocator模板参数相同。 - T.C.
因为它是一个模板参数。容器可以(并且通常会用于元数据)使用重新绑定的allocator_type,但它不能重新定义allocator_type。 - Ben Voigt
@BenVoigt 理论上没有任何阻止标准规定 allocator_typetypename allocator_traits<Allocator>::template rebind_alloc<value_type> 的内容,只是它没有这么做。 - T.C.
@T.C.:当然可以,但实际上并没有这样做。而且这也不会给实现者留下灵活性。它确实为实现者使用反弹版本的分配器进行实际分配留下了灵活性。 - Ben Voigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接