为何std::vector无法容纳带const/volatile限定或引用类型的元素?
为何std::vector无法容纳带const/volatile限定或引用类型的元素?
有观点提到vector这类容器的元素类型必须具备可赋值性:
vector这类容器的元素类型必须具备可赋值性。引用类型不可赋值(只能在声明时初始化一次,后续无法让其引用其他对象)。其他不可赋值的类型也不能作为容器元素,例如vector<int&>是不被允许的。
但以下代码中,class test显式删除了拷贝构造和赋值运算符,完全不具备可赋值性,却能通过编译:
class test { public: test(test &) = delete; test &operator=(test &) = delete; }; int main() { std::vector<test> vec; }
另有观点认为限制来自std::vector<T, std::allocator<T>>的分配器,但观察vector的实现代码,有两个static_assert直接写在vector类内部而非分配器中:
template<typename _Tp, typename _Alloc = std::allocator<_Tp> > class vector : protected _Vector_base<_Tp, _Alloc> { #if __cplusplus >= 201103L static_assert(is_same<typename remove_cv<_Tp>::type, _Tp>::value, "std::vector must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same<typename _Alloc::value_type, _Tp>::value, "std::vector must have the same value_type as its allocator"); # endif #endif
这两个断言才是限制元素类型的真正原因吗?
此外,为何volatile作为限定符如此特殊,不能用作vector的元素限定?
注:仅希望了解原因,无需提供规避方案。
内容的提问来源于stack exchange,提问作者shengguo lu
相关产品推荐
相关产品推荐

