const auto和auto const如何应用于指针?

时间:2017-11-09 22:00:35

标签: c++ c++11

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

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;
}

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

1 个答案:

答案 0 :(得分:9)

在此示例中,import matplotlib.pyplot as plt vals,poly = range(-60,60), range(-60,60) plt.plot(vals, poly, label='some graph') roots = [-1,1,2] mark = [vals.index(i) for i in roots] plt.plot(roots,[poly[i] for i in mark], ls="", marker="o", label="points") plt.show() 正在应用于任何const推理,这意味着两者都会导致类型为auto的对象,因为int * const本身就是推断auto。您想象的顺序取决于您是否以int *auto const撰写,而const auto和{{1}的方式相同是一样的。

考虑这种情况的更简单方法可能是尝试以下方法:

int const

就C ++而言,此示例中的任何变量(其名称仅因附加数字而不同)都是等效类型。请注意如何更改const int出现的位置并不会影响推断的类型。这是因为&#34;从右到左阅读&#34;用于确定如何声明类型的规则基于如何编写原始类型:一旦使用这样的结构(或者,如您所见,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; ),规则变得更加简单。

我的直觉是,因为你的问题意味着你需要对类型系统进行这种细粒度的控制,你应该在{{1}上使用constauto就像我在这里展示的那样,并使用它来声明你的类型,因为它更容易一目了然地知道using是什么而不是看{{1}是的。特别是因为它可以防止这样的愚蠢错误:

typedef

pointer<T>在技术上也解决了这个问题,但正如您在示例中所显示的那样,({1}}是否正在应用于指针仍然不明确(对您而言)本身,或它指向的对象,而在这种情况下,没有更多的歧义。