C++11 auto关键字介绍
2015-12-27 16:09
344 查看
C++11 auto关键字介绍
1.auto关键字的作用
提示编译器对变量的类型进行自动推导,能够增加代码的灵活度,减少代码的书写量2.auto关键字的注意事项
当不声明为引用时,auto的初始化表达式即使是引用,编译器也不会将其推导为对应的类型的引用。在实际编码中一定要注意。具体分析请见 auto关键字的推导规则在实际编码中,建议显式的声明指针和引用。这样既能够增强代码的可读性,也能够避免引用失效的情况。
int x = 25; auto *a = &x;//显式的声明指针 auto &b = x;//显式的声明引用
3.auto关键字的使用场景
3.1自动推导stl容器的迭代器
vector<int> aa; for (vector<int>::iterator iter = aa.begin(); iter != aa.end(); ++iter){} //等同于 for (auto iter = aa.begin(); iter != aa.end();++iter){}
3.2增强代码的灵活性
class Window { public: static int get() { return 1; } }; class Bar { public: static string get() { string str = "hello auto"; return str; } }; template<class T> void Func() { auto val = T::get(); // ... } int main() { Func<Window>(); Func<Bar>(); return 0; }
4.auto关键字的推导规则
当不声明为引用时,auto的初始化表达式即使是引用,编译器也不会将其推导为对应的类型的引用,auto的推导结果等同于初始化表达式去除引用和const限定符后的类型。见d当声明为引用时,auto的推导结果将保留初始化表达式的const或者非const属性,见c,g,h
初始化表达式为指针类型时,auto的推导结果能够推导出正确的类型,其结果能够保留初始化表达式的const或非const属性,见a,b,i,j
#include <iostream> using namespace std; int main() { int x = 0; auto *a = &x;//类型为int*,auto为int ++(*a); cout << "after ++(*a) *a:" << *a << " x:" << x << endl; auto b = &x;//类型为int*,auto为int* ++(*b); cout << "after ++(*b) *b:" << *b << " x:" << x << endl; auto &c = x;//类型为int&,auto为int ++c; cout << "after ++c c:" << c << " x:" << x << endl; auto d = c;//类型为int,auto为int ++d; cout << "after ++d d:" << d << " x:" << x << endl; const auto e = x;//类型为const int,auto为int //++e; error C3892: “e”: 不能给常量赋值 auto f = e;//类型为int,auto为int ++f; cout << "after ++f f:" << f << " x:" << x << endl; const auto &g = x;//类型为const int&,auto为int //++g; error C3892: “g”: 不能给常量赋值 auto& h = g;//推导为const int&,auto为const int //++h; error C3892: “g”: 不能给常量赋值 auto *i = &e; //++(*i); error C3892: “i”: 不能给常量赋值 auto j = i; //++(*j); error C3892: “j”: 不能给常量赋值 return 0; }
运行结果如下:
5.auto关键字的使用限制
5.1不能用于函数参数
//void func(auto a = 1){} error C3533: 参数不能为包含“auto”的类型
5.2不用用于非静态成员变量
struct Foo { //auto v1 = 0; error C2853: “v1”: 非静态数据成员不能具有包含“auto”的类型 static const auto v0 = 25; };
5.3无法定义数组
int arr[10] = { 0 }; //auto rr[10] = arr; error C3318: “auto [10]”: 数组不能具有其中包含“auto”的元素类型
5.4无法推导出模板参数
vector<int> aa; //vector<auto> bb = aa; error C3539 : 模板参数不能为包含“auto”的类型
6.感谢
本文为《深入应用C++11代码优化与工程级应用》的读书笔记。感谢该书作者的辛勤劳动和分享。相关文章推荐
- GC基本算法及C++GC机制
- getchar()函数使用要点
- C++中引用(&)的用法和应用实例
- 有n个整数,指定位置m处插入g个值(用指针和函数)
- C++小题(四)
- C++习题 虚函数-计算图形面积
- C/C++中const关键字详解
- C++学习:构造函数
- C++之路起航——标准模板库(queue)
- C++,清楚明白的解释
- 关于STL中trivial destroctor的小记
- C语言学习笔记------伊能C语言学习笔记-----外部函数
- [LeetCode-230]Kth Smallest Element in a BST
- C语言学习笔记-------伊能C语言学习笔记------静态函数初步
- 《C++ Primer》读书笔记之第15章:面向对象编程
- c++14可以直接书写二进制字面常量了
- C++ 类的成员函数定义在.h中为什么会产生函数重定义错误?
- c++中的转义字符
- C++中string、int常见类型转换(含代码演示)
- C++编译器