C++11引入了类型说明符auto,它给我们带来了方便,但有时也会因为使用不当而造成错误。
说明:
- auto只能用于识别类型。如int,string,类类型等
- auto不能代替引用&
auto与指针,引用的关系
9 #include <iostream>
10
11 int x;
12 int *y = &x;
13
14 int func()
15 {
16 std::cout <<__func__<<std::endl;
17 }
18
19 int& foo()
20 {
21 std::cout <<__func__<<std::endl;
22 }
23
24
25
26 int main()
27 {
28 auto *a = &x; //int*
29 auto &b = x; //int&
30 auto c = y; //int*
31 auto *d = y; //int*
32
33 auto *e = &func(); //编译失败,指针不能指向一个临时的变量(纯右值)
34 auto &f = func(); //编译失败,非const的左值引用不能喝一个临时变量(纯右值)绑定
35 auto g = foo(); //int
36 auto &h = foo(); //int&
37
38 return 0;
39 }
输出:
[xqs@localhost ~/src]g++ -std=gnu++11 test.cpp -o test -w
test.cpp: 在函数‘int main()’中:
test.cpp:33:18: 错误:单目‘&’的操作数必须是左值
auto *e = &func();//编译失败,指针不能指向一个临时的变量(纯右值)
test.cpp:34:17: 错误:用类型为‘int’的右值初始化类型为‘int&’的非常量引用无效
auto &f = func();//编译失败,非const的左值引用不能与一个临时变量(纯右值)绑定