此文为转发web
连接:http://blog.csdn.net/huang_xw/article/details/8760403编程
C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,因为使用极少且多余,在C++11中已被删除。先后两个标准的auto,彻底是两个概念。
数组
1. 自动类型推断
auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。经过auto的自动类型推断,能够大大简化咱们的编程工做。下面是一些使用auto的例子。
app
- #include <vector>
- #include <map>
-
- using namespace std;
-
- int main(int argc, char *argv[], char *env[])
- {
-
-
- auto a = 10;
- auto c = 'A';
- auto s("hello");
-
-
- map<int, map<int,int> > map_;
- map<int, map<int,int>>::const_iterator itr1 = map_.begin();
- const auto itr2 = map_.begin();
- auto ptr = []()
- {
- std::cout << "hello world" << std::endl;
- };
-
- return 0;
- };
-
- template <class T, class U>
- void Multiply(T t, U u)
- {
- auto v = t * u;
- }
2. 返回值占位
- template <typename T1, typename T2>
- auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)
- {
- return t1+t2;
- }
- auto v = compose(2, 3.14);
3.使用注意事项
①咱们可使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto
函数
- auto k = 5;
- auto* pK = new auto(k);
- auto** ppK = new auto(&k);
- const auto n = 6;
②用auto声明的变量必须初始化
oop
③auto不能与其余类型组合连用
this
④函数和模板参数不能被声明为auto
spa
- void MyFunction(auto parameter){}
-
- template<auto T>
- void Fun(T t){}
⑤定义在堆上的变量,使用了auto的表达式必须被初始化
.net
- int* p = new auto(0);
- int* pp = new auto();
-
- auto x = new auto();
-
- auto* y = new auto(9);
- auto z = new auto(9);
⑥觉得auto是一个占位符,并非一个他本身的类型,所以不能用于类型转换或其余一些操做,如sizeof和typeid
指针
- int value = 123;
- auto x2 = (auto)value;
-
- auto x3 = static_cast<auto>(value);
⑦定义在一个auto序列的变量必须始终推导成同一类型
- auto x1 = 5, x2 = 5.0, x3='r';
⑧auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型
- const int i = 99;
- auto j = i;
- j = 100
-
- auto& k = i;
- k = 100;
-
⑨auto会退化成指向数组的指针,除非被声明为引用
- int a[9];
- auto j = a;
- cout<<typeid(j).name()<<endl;
-
- auto& k = a;
- cout<<typeid(k).name()<<endl;