为什么const指针的向量在c ++ 17中起作用

Pin*_*iid 3 c++ vector c++11

我看到了这个答案:C ++ 11允许vector<const T>吗?解释如何,你应该使用const Tstd::vector。我尝试了此操作,std::vector<const int> int_vector并得到了编译器错误,这是预期的。但是,如果我创建一个,std::vector<const CustomType*> custom_type_vector我可以毫无问题地使用它。这是否意味着c ++允许将const指针作为a内的元素,std::vector但不允许const Tin std::vector

最小的可复制示例

std::vector<const int> vec_a; // compiler will complain this.
std::vector<const int*> vec_a; // compiler will accept this.
Run Code Online (Sandbox Code Playgroud)

使用的错误日志std::vector<const int>是:

/usr/include/c++/7/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 int; __gnu_cxx::new_allocator<_Tp>::const_pointer = const int*; __gnu_cxx::new_allocator<_Tp>::const_reference = const int&]' cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/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 int; __gnu_cxx::new_allocator<_Tp>::pointer = const int*; __gnu_cxx::new_allocator<_Tp>::reference = const int&]'
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:125:19: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
  ::operator delete(__p);
  ~~~~~~~~~~~~~~~~~^~~~~
Run Code Online (Sandbox Code Playgroud)

我的编译器版本是gcc版本7.4.0(Ubuntu 7.4.0-1ubuntu1〜18.04.1)

Tas*_*Tas 8

正如m_pOatrix在注释中正确指出的那样std::vector<const CustomType*>它不是const指针的向量,而是const对象的指针的向量,这是允许的。

如果改为使用const指针,则将不允许这样做:

std::vector<Foo> f; // allowed
std::vector<const Foo> f; // disallowed
std::vector<const Foo*> f;// allowed
std::vector<Foo* const> f; // disallowed
Run Code Online (Sandbox Code Playgroud)

诀窍const是它适用于紧接在它左边的东西,或者如果它在开头(通常是这样),则它适用于第一件事。

const Foo*; // pointer to const Foo, same as Foo const*
Foo* const; // const pointer to Foo
Run Code Online (Sandbox Code Playgroud)