c++ - 为什么 const 指针的向量在 c++17 中工作
问题描述
我看到了这个答案:C++11 允许vector<const T>
吗?解释了您不应该如何在. 我尝试了这个并得到了编译器错误,这是预期的。但是,如果我创建一个,我可以毫无问题地使用它。这是否意味着 c++ 允许 const 指针作为 a 内的元素但不允许in ?const T
std::vector
std::vector<const int> int_vector
std::vector<const CustomType*> custom_type_vector
std::vector
const T
std::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)
解决方案
正如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
推荐阅读
- azure - 在没有 SAS 令牌的情况下创建并连接到 Azure Stage
- automation - QT桌面应用程序如何自动化(跨平台Win+Mac)?
- aws-lambda - 使用 Lambda 将 pdf base64 上传到 Amazon S3
- e2e-testing - 如何使用 webdriver-io 找到匹配多个数据属性的元素?
- javascript - 我得到错误:“TypeError:无法读取未定义的属性'2'。”在javascript测试文件中
- google-sheets - 如何使用 Google 表格、Google 财经和 Sparkline 根据我当前的资产创建净值图表?
- java - 无论如何调整 Feed Adapter 以根据事件采取行动?
- php - Laravel 规则整数防止溢出
- typescript - Vue 类组件无法从构造函数访问数据属性
- excel - Excel 到 Access 文件上传