1
2
3
int count = 10;
int& countRef = count;
auto myAuto = countRef; // 普通的int,非引用

您可能会认为 myAuto 是一个 int 引用,但它不是。

验证:

1
2
3
4
5
countRef = 11;
cout << count << " ";

myAuto = 12;
cout << count << endl;

只是一个 int。因为输出为 11 11,而不是 11 12;

如果 auto 尚未删除此引用,则会出现此情况。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
map<int,list<string>>::iterator i = m.begin();
auto i = m.begin(); // 就是如此简单……

#include <deque>
using namespace std;

int main()
{
deque<double> dqDoubleData(10, 0.1);

for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter) // 注意是 ++iter
{ /* ... */ }

for (auto elem : dqDoubleData)
{ /* ... */ }

for (auto& elem : dqDoubleData)
{ /* ... */ }

for (const auto& elem : dqDoubleData)
{ /* ... */ }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double x = 12.34;
auto *y = new auto(x), **z = new auto(&x);

auto x = 1, *y = &x, **z = &y; // Resolves to int.
auto a(2.01), *b (&a); // Resolves to double.
auto c = 'a', *d(&c); // Resolves to char.
auto m = 1, &n = m; // Resolves to int.

int f(int x) { return x; }
int main()
{
auto x = f(0); // int x
const auto & y = f(1); // const int & y 引用

int (*p)(int x);
p = f;
auto fp = p; // 返回值为 int 类型的函数的指针
}