我尝试了一些代码,并想知道constC++中的限定符在使用时如何应用于指针类型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;
}
Run Code Online (Sandbox Code Playgroud)
我意识到有一个类似的问题,询问它们是否相同,我更具体地询问这里的规则是什么,它适用于推断结束指针类型.
Xir*_*ema 10
在这个例子中,const正在应用于任何auto推论,这意味着两个使用都会导致类型的对象int * const,因为auto它本身就是推导int *.您所想象的订货需要根据您是否写到位auto const或const 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;
Run Code Online (Sandbox Code Playgroud)
就C++而言,此示例中的任何变量(其名称仅因附加数字而不同)是等效类型.请注意如何更改const显示的位置不会影响推断的类型.这是因为用于确定如何声明类型的"从右向左读取"规则基于如何编写原始类型:一旦使用这样的结构(或者,如您所观察到的auto),规则变得更加简单.
我的直觉是,由于您的问题排序意味着你需要这种在类型系统精细控制的反正,你应该使用一个using或typedef上pointer<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
Run Code Online (Sandbox Code Playgroud)
auto技术上也解决了这个问题,但正如你在你的例子中所展示的那样,对你来说,它是否仍然是模糊的(无论const是)是应用于指针本身,还是指向它所指向的对象,而在这种情况下,没有更多的模糊性.