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

粉红色

我看到了这个答案: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.

使用的错误日志为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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么在int指针的const向量中取消引用的元素是可变的?

为什么调整向量*(在向量*数组中)的指针的大小比向量(在向量数组中)的指针大小更快?

为什么在C ++中没有像const指针那样的const引用?

为什么创建const指针集合在a.iter()中的for val而不是a.iter()。map(| val | val)中起作用?

为什么c++地址中的向量不能通过原始指针访问

为什么这不起作用?Android中的空指针

为什么C ++中auto_ptr的二维向量不起作用?

如何在C ++中为对象的指针的const向量赋值?

如果要保护向量的修改,如果尝试使用const子句,为什么不起作用?

强制转换中的中间指针必须是“ const限定”的-为什么?

为什么const不起作用

在c ++中将元素添加到空向量中:为什么push.back有效,[]不起作用

为什么采用char指针指针的函数不起作用?

为什么单行XOR交换在Javascript中不起作用,而在C ++中起作用?

为什么“ for”在“ go”中不起作用?

在PHP中为什么不起作用

为什么“setOnClickListener (this)”在“for in”中不起作用?

为什么允许在初始化列表中从const指针到const到const指针到非常量的转换

如果条件在c中起作用,为什么在printf里面?

为什么 C 中的这个 while 循环不起作用?

为什么隐藏方法在C#中不起作用

为什么退格键'\ b'在C ++中不起作用?

为什么此C代码在JavaScript中不起作用?

为什么序列迭代在C宏中起作用?

为什么AddLast在C#链接列表中起作用?

C ++中的多态性为什么不起作用?

为什么“函数尝试”在 C++ 中不起作用?

为什么if else结构在c ++中不起作用?

out 参数在 C# 中不起作用。为什么?