具有自定义分配器的const T STL容器格式不正确吗?

osu*_*ka_ 5 c++ language-lawyer c++14

采取以下代码段:

#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 language restriction. It is also my understanding that since templates are instantiated at compile time, the default value for the vector's allocator (i.e., std::allocator<const T>) is never instantiated - and that, therefore, the last line does not break that rule.

Ignoring the use cases and alternatives (and the fact that const std::vector<int> probably solves your problem), and given a valid my_custom_allocator: is std::vector<const int, my_custom_allocator> really ill-formed?

Mic*_*zel 5

我认为它仍然是不正确的。根据[allocator.requirements],分配器应该与定义为的T类型的对象一起使用

任何cv未限定的对象类型

基于此,在我看来,任何可以使用的东西都const T不能满足作为分配器的要求,因此不能用作标准容器的分配器......

  • [allocator.requirements] 要求分配器的 `value_type` 是 *cv* 未限定的对象类型。因此,这不合法…… (3认同)