在 C++ 中,使用 auto
关键字自动推导变量的类型时,会自动忽略掉引用、const、volatile 等修饰符,只保留基本类型,例如 int、double、char 等。因此,如果使用 auto a = getVal()
这样的语句进行自动推导时,变量 a 的类型会被推导为 int,而不是 int&
#include <iostream>
using namespace std;
int gA = 10;
int& getVal() {
cout << "gA:" << &gA << endl;
return gA;
}
int main() {
auto a = getVal();
cout << "a: " << &a << endl;
auto& b = getVal();
cout << "b: " << &b << endl;
return 0;
}
gA:0x5612c500d010
a: 0x7ffe1cd1730c
gA:0x5612c500d010
b: 0x5612c500d010