一、 C++11特性之auto

auto

C++11中引入的auto主要有两种用途:自动类型推断和返回值占位

auto的自动类型推导,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推导,可以大大简化我们的编程工作

auto实际上实在编译时对变量进行了类型推导,所以不会对程序的运行效率造成不良影响

另外,似乎auto并不会影响编译速度,因为编译时本来也要右侧推导然后判断与左侧是否匹配。

auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。

1. 自动类型推断

    auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <vector>  
 4 #include <map>  
 5 
 6 using namespace std; 
 7 
 8 int main(int argc, char *argv[], char *env[])  
 9 {  
10     //  auto a;                 // 错误,没有初始化表达式,无法推断出a的类型  
11     //  auto int a = 10;        // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。  
12 
13     // 1. 自动帮助推导类型  
14     auto a = 10;  
15     auto c = 'A';  
16     auto s("hello");
17     auto i = 1;
18     auto d = 1.0;
19     auto str = "Hello World";
20     auto ch = 'A';
21     auto func = less<int>();
22     vector<int> iv;
23     auto ite = iv.begin();
24     
25 
26     // 2. 类型冗长  
27     map<int, map<int,int> > map_;  
28     map<int, map<int,int>>::const_iterator itr1 = map_.begin();  
29     const auto itr2 = map_.begin();  
30     auto ptr = []()  
31     {
32         cout<<"hello world"<<endl;
33     }; 
34 
35     return 0;  
36 };  
37 
38     // 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,  
39     // 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。  
40 template <class T, class U>  
41 void Multiply(T t, U u)  
42 {  
43     auto v = t * u;  
44 }
45 /*
46 //auto不光有以上的应用,它在模板中也是大显身手,比如下例这个加工产品的例子中,如果不使用auto就必须声明Product这一模板参数:
47 template <typename Product, typename Creator>
48 void processProduct(const Creator& creator)
49 {
50     Product* val = creator.makeObject();
51     // do somthing with val
52 }       
53 //如果使用auto,则可以这样写:
54 template <typename Creator>
55 void processProduct(const Creator& creator)
56 {
57     auto val = creator.makeObject();
58     // do somthing with val
59 }
60 //抛弃了麻烦的模板参数,整个代码变得更加整洁了。
61 */

2. 返回值占位

1 template <typename T1, typename T2>  
2 auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)  
3 {  
4    return t1+t2;  
5 }  
6 auto v = compose(2, 3.14); // v's type is double 

3.使用注意事项

①我们可以使用valatile,pointer(*),reference(&),rvalue reference(&&)来修饰auto

1 auto k = 5;  
2 auto* pK = new auto(k);  
3 auto** ppK = new auto(&k);  
4 const auto n = 6;  
 

②用auto声明的变量必须初始化

1 auto m; // m should be intialized   

③auto不能与其他类型组合连用

 

1 auto int p; // 这是旧auto的做法。

 

④函数和模板参数不能被声明为auto

1 void MyFunction(auto parameter){} // no auto as method argument  
2   
3 template<auto T> // utter nonsense - not allowed  
4 void Fun(T t){}  

⑤定义在堆上的变量,使用了auto的表达式必须被初始化

1 int* p = new auto(0); //fine  
2 int* pp = new auto(); // should be initialized  
3    
4 auto x = new auto(); // Hmmm ... no intializer  
5      
6 auto* y = new auto(9); // Fine. Here y is a int*  
7 auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)  

⑥auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid

1 int value = 123;  
2 auto x2 = (auto)value; // no casting using auto  
3   
4 auto x3 = static_cast<auto>(value); // same as above   

⑦定义在一个auto序列的变量必须始终推导成同一类型

1 auto x1 = 5, x2 = 5.0, x3='r';  // This is too much....we cannot combine like this 

⑧auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型

1 const int i = 99;  
2 auto j = i;       // j is int, rather than const int  
3 j = 100           // Fine. As j is not constant  
4   
5 // Now let us try to have reference  
6 auto& k = i;      // Now k is const int&  
7 k = 100;          // Error. k is constant  
8   
9 // Similarly with volatile qualifer  

⑨auto会退化成指向数组的指针,除非被声明为引用

1 int a[9];  
2 auto j = a;  
3 cout<<typeid(j).name()<<endl; // This will print  int*  
4   
5 auto& k = a;  
6 cout<<typeid(k).name()<<endl; // This will print  int [9]
在c++中,typeid用于获知一个变量的具体类型。注意:typeid是操作符,不是函数!)
运行时获知变量类型名称,可以使用 typeid(变量).name,需要注意不是所有编译器都输出"int"、"float"等之类的名称,对于这类的编译器可以这样使用:float f = 1.1f; if( typeid(f) == typeid(0.0f) ) ……
posted @ 2014-12-18 22:56  击进的Cocos  阅读(393)  评论(0)    收藏  举报