const_iterator const 类型容器的类型

const_iterator type of a container of const types

如果我编译下面的代码:

#include <list>

using iter_t = std::list<const unsigned>::const_iterator;

int main(int, char**) {
  return 0;
}

我得到以下编译错误:

In file included from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/x86_64-apple-darwin13.4.0/bits/c++allocator.h:33:0,
             from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/allocator.h:46,
             from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/list:61,
             from main.cpp:1:
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<const unsigned int>':
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/allocator.h:92:11:   required from 'class std::allocator<const unsigned int>'
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/stl_list.h:315:9:   required from 'class std::_List_base<const unsigned int, std::allocator<const unsigned int> >'
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/stl_list.h:447:11:   required from 'class std::list<const unsigned int>'
main.cpp:3:41:   required from here
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h:93:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const unsigned int; __gnu_cxx::new_allocator<_Tp>::const_pointer = const unsigned int*; __gnu_cxx::new_allocator<_Tp>::const_reference = const unsigned int&]' cannot be overloaded
   address(const_reference __x) const _GLIBCXX_NOEXCEPT
   ^
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h:89:7: error: with '_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const unsigned int; __gnu_cxx::new_allocator<_Tp>::pointer = const unsigned int*; __gnu_cxx::new_allocator<_Tp>::reference = const unsigned int&]'
   address(reference __x) const _GLIBCXX_NOEXCEPT
   ^

如果我将容器类型从 std::list 更改为 std::vectorstd::dequestd::forward_list,我会收到大致相同的错误消息。如果我将模板参数从 const unsigned 更改为 unsigned,它可以正常编译。

这是怎么回事?我不明白为什么它不能编译。

Visual C++ 2015 给出了明确的诊断

The C++ Standard forbids containers of const elements because allocator<const T> is ill-formed.

据我了解,这是因为分配器的 allocate 方法 returns 指向未初始化 T 项目数组的指针,如果 Tconst 那么这些项目将永远无法初始化。

我找不到任何明确的声明 allocator<const T> 格式错误,所以这可能是语义的结果。

正如 Dieter Lücking 所指出的 ,在提供地址 reference 和 [=] 的两个成员函数之间存在 const 类型 T 的直接冲突20=],因为当类型为 const.

时它们是相等的