c++ - const auto 和 auto const 如何应用于指针?

标签 c++ c++11

我尝试了一些代码,想知道在使用 auto 时 C++ 中的 const 限定符如何应用于指针类型。

int main()
{
  int foo = 1;
  int bar = 2;

  //Expected: const int * ptr_to_const_int = &foo;
  const auto ptr_to_const_int = &foo;

  //Expected: int * const const_ptr_to_int = &foo;
  auto const const_ptr_to_int = &foo;


  *ptr_to_const_int = 3; //Thought this would error
  //ptr_to_const_int = &bar; This does error.
  *const_ptr_to_int = 3;

  return 0;
}

我意识到有一个类似的问题询问它们是否相同,我想更具体地询问这里应用于推导结束指针类型的规则是什么。

最佳答案

在这个例子中,const正在应用于任何auto推导,这意味着两种使用都会导致类型为 int * const 的对象,因为 auto靠自己推导int * .您想象的排序是根据您是否编写它来进行的 auto constconst auto不会发生,与 int const 相同和 const int是一样的。

考虑这个问题的更简单方法可能是尝试以下操作:

template<typename T>
using pointer = T*;

pointer<int> ptr_to_int = new int;
const pointer<int> const_ptr_to_int = new int;
pointer<const int> ptr_to_const_int = new int;
const pointer<const int> const_ptr_to_const_int = new int;

pointer<int> const const_ptr_to_int2 = new int;
pointer<int const> ptr_to_const_int2 = new int;
pointer<const int> const const_ptr_to_const_int2 = new int;

pointer<int const> const const_ptr_to_const_int3 = new int;

就 C++ 而言,此示例中的任何变量,其名称仅因附加数字而不同,都是等效类型。注意如何更改 const 的位置出现不影响推导的类型。这是因为用于确定类型声明方式的“从右到左读取”规则是基于原始类型的编写方式:一旦您使用这样的构造(或者,如您所见, auto ),规则就变成了简单多了。

我的直觉是,既然你的问题有点暗示你无论如何都需要对类型系统进行这种细粒度的控制,你应该使用 usingtypedefpointer<T>就像我在这里展示的那样,并用它来声明你的类型,因为它更容易一目了然地知道什么是 const pointer<int>是比是看什么int *const是。特别是因为它可以防止像这样的愚蠢错误:

int * a_ptr, b_ptr, c_ptr; //Oops! We meant b_ptr and c_ptr to also be pointers, but
//they ended up being regular ints!

pointer<int> a_ptr, b_ptr, c_ptr; //All of these are pointers, as we expected them to be

auto技术上也解决了这个问题,但是正如您在示例中所展示的那样,const 是否仍然不明确(对您而言)被应用到指针本身,或者它指向的对象,而在这种情况下,没有更多的歧义。

关于c++ - const auto 和 auto const 如何应用于指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212317/

相关文章:

c++ - 如何找到对集合中一对之间的元素?

c++ - clang 不知道 std::atomic_bool,但 XCode 知道

c++ - 尝试使用 std::result_of 时出现编译错误

c++ - 如何在具有透明度的大型广告牌渲染中避免距离排序

c++ - 如何为派生类通用地实现复制构造函数?

c++ - 如何在匿名命名空间中使用带有免费功能的谷歌测试?

c++ - 为什么 std::tie 没有标记为 C++14 的 constexpr?

c++ - 使用样式表在QMainWindow上的Qt 5.10半透明背景

C++ lambda 按值语义捕获?

c++ - 对于一个参数