首页 > 解决方案 > 为什么 const 指针的向量在 c++17 中工作

问题描述

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

最小可重现示例

std::vector<const int> vec_a; // compiler will complain this.
std::vector<const int*> vec_a; // compiler will accept this.

使用的错误日志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);
  ~~~~~~~~~~~~~~~~~^~~~~

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

标签: c++c++11vector

解决方案


正如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

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

const Foo*; // pointer to const Foo, same as Foo const*
Foo* const; // const pointer to Foo

推荐阅读