【发布时间】:2019-03-22 18:50:24
【问题描述】:
取如下代码sn-p:
#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;
为什么 X 无法编译? MSVS 2017 展示
错误 C2338(失败的静态断言):C++ 标准禁止 const 元素的容器,因为分配器格式错误。
据我了解,这不一定正确。
根据 20.5.3.5 [allocator.requirements](和 many SO questions),const T 的分配器格式不正确 - 但据我了解,也可以使用 define an allocator that only works with a single type(意思是,非模板分配器)。这避免了语言限制,尽管有点迂腐。我的理解也是,由于模板是在编译时实例化的,因此向量分配器的默认值(即std::allocator<const T>)永远不会被实例化——因此,最后一行不会违反该规则。
忽略用例和替代方案(以及const std::vector<int> 可能解决您的问题的事实),并给出有效的my_custom_allocator:std::vector<const int, my_custom_allocator> 真的格式不正确吗?
【问题讨论】:
-
我相信这使得
my_custom_allocator不是分配器。 -
适用于一种类型的分配器,但适用于哪一种?容器需要的那个?
-
@curiousguy 是的,否则行为是不确定的。
-
@osuka_ 怎么能提前知道容器要分配哪种类型的对象?
-
@curiousguy 你会知道的,因为你已经实现了它。然而,不管怎样,问题不在于分配器本身,而在于容器类型的合法性,例如上面讨论的容器类型。
标签: c++ c++14 language-lawyer