【发布时间】:2022-04-26 18:36:09
【问题描述】:
我尝试了一些代码,想知道 C++ 中的 const 限定符在使用 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;
}
我意识到有一个类似的问题询问它们是否相同,我更具体地说是问这里适用于推断结束指针类型的规则是什么。
【问题讨论】:
-
它同样适用于别名:
using T = int *; const T->int *const。 -
const auto和auto const将是同一类型。 Example -
auto使用 template argument deduction 的规则