我看到了这个答案:C ++ 11允许vector<const T>
吗?解释如何,你应该不使用const T
的std::vector
。我尝试使用此方法,但出现std::vector<const int> int_vector
了编译器错误,这是预期的。但是,如果我创建一个,std::vector<const CustomType*> custom_type_vector
我可以毫无问题地使用它。这是否意味着c ++允许将const指针作为a内的元素,std::vector
但不允许const T
in 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句