【问题标题】:Is an STL Container of const T with a custom allocator ill-formed?带有自定义分配器的 const T 的 STL 容器格式不正确吗?
【发布时间】: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&lt;const T&gt;)永远不会被实例化——因此,最后一行不会违反该规则。

忽略用例和替代方案(以及const std::vector&lt;int&gt; 可能解决您的问题的事实),并给出有效的my_custom_allocator:std::vector&lt;const int, my_custom_allocator&gt; 真的格式不正确吗?

【问题讨论】:

  • 我相信这使得my_custom_allocator 不是分配器。
  • 适用于一种类型的分配器,但适用于哪一种?容器需要的那个?
  • @curiousguy 是的,否则行为是不确定的。
  • @osuka_ 怎么能提前知道容器要分配哪种类型的对象?
  • @curiousguy 你会知道的,因为你已经实现了它。然而,不管怎样,问题不在于分配器本身,而在于容器类型的合法性,例如上面讨论的容器类型。

标签: c++ c++14 language-lawyer


【解决方案1】:

我认为它仍然是不正确的。根据[allocator.requirements],分配器应该使用T 类型的对象,即defined to be

任何cv-不合格的对象类型

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

【讨论】:

  • 但是理论上的custom_const_allocator&lt;T&gt; 会是 cv-unqualified T - 但会是 Allocator::value_type = const T?
  • [allocator.requirements] 要求分配器的 value_type 是 cv 非限定对象类型。因此,这是不合法的……
  • 啊,你似乎是对的。 value_type 本身没有任何要求,但由于它必须与 T相同,因此它似乎是非法的。
  • 好吧,value_type 必须与T 相同(其中T 是分配器的分配器类型)我称之为对value_type 施加的要求… ;-)
  • 你刚刚向我证明了我既不会写 C++,也不会写英文。多么美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 2012-07-07
相关资源
最近更新 更多