容器需求已从C++ 03更改为C++ 11.虽然C++ 03有一揽子要求(例如复制构造性和向量的可赋值性),但C++ 11定义了每个容器操作的细粒度要求(第23.2节).
因此,只要您只执行某些不需要赋值的操作(构造并且push_back是这样的操作),您可以例如在向量中存储可复制构造但不可赋值的类型(例如具有const成员的结构).; insert不是).
我想知道的是:这是否意味着标准现在允许vector<const T>?我没有看到任何理由它不应该 - const T就像具有const成员的结构一样,是一种可复制构造但不可分配的类型 - 但我可能错过了一些东西.
(让我觉得我可能错过了一些东西的部分原因是,如果你试图实例化vector<const T>,那gcc trunk会崩溃并烧掉,但是vector<T>对于T有const成员的地方来说很好).
Are there any Difference between const char* p and char const* p
Run Code Online (Sandbox Code Playgroud) 采取以下代码段:
#include <vector>
std::vector<int> good;
//illegal, because std::allocator<const T> is ill-formed
std::vector<const int> bad;
//fails to compile under MSVS 2017
std::vector<const int, my_custom_allocator> X;
Run Code Online (Sandbox Code Playgroud)
为什么X无法编译?MSVS 2017展示
错误C2338(失败的静态断言):由于分配程序的格式不正确,因此C ++标准禁止使用const元素的容器。
据我了解,这不一定是正确的。
According to 20.5.3.5 [allocator.requirements] (and many SO questions), an allocator of a const T is ill-formed - but as I understand it, it is also possible to define an allocator that only works with a single type (meaning, a non-templated allocator). This avoids, albeit in a slightly pedantic way, the …