`auto pp` 和 `auto *ppp` 有什么区别?

What's the difference between `auto pp` and `auto *ppp`?

int foo = 11;
int *p = &foo;

auto pp = p;
auto *ppp = p;

cout << pp << endl;
cout << ppp << endl;

此程序将为 ppppp 生成相同的输出,但为什么呢? auto推导出变量应该是int,所以我认为ppp的声明是对的。但是 ppppp 具有相同的值...

输出:

0x61fefc
0x61fefc

在这种特殊情况下,autoauto * 没有区别。在 auto pp = p; 的情况下,类型将推导为 int *,而在 auto *ppp = p; 的情况下,类型将推导为 int

auto qualifier:

For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. [...]

请注意,与 auto 不同,auto * 将仅推导指针类型。

在您显示的特定示例中,没有区别。但是想象一下,您稍后会添加两个 const 限定符,如下所示:

const auto pp = p;
const auto *ppp = p;

还是老样子?事实证明,这与

相同
int * const pp = p; // pointer is readonly
const int *ppp = p; // pointer is readonly

因为在auto pp = p中,auto匹配int*作为一个整体,而const修改其左边的内容(或者右边的内容,如果没有的话在它的左边)。相反,在auto *ppp = p中,auto匹配int,这就是const适用的。

由于这个显着差异,并且因为我们应该尽可能使用 const 变量,所以我建议您在对指针变量使用类型推导时始终使用 auto*。没有办法 const 限定指针本身而不是指针对象,如果你想 const 限定两者,这可以通过

const auto * const pppp = p;

没有 *.

就无法工作