C++11新特性之auto的使用

来源:互联网 发布:java反射调用泛型方法 编辑:程序博客网 时间:2024/05/20 00:15

前言

C++是一种强类型语言,声明变量时必须明确指出其类型。但是,在实践中,优势我们很难推断出某个表达式的值的类型,尤其是随着模板类型的出现,要想弄明白某些复杂表达式的返回类型就变得更加困难。为了解决这个问题,C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。

一、自动类型推断

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <vector>
#include <map>
  
usingnamespacestd;
  
intmain(intargc,char*argv[],char*env[])
{
// auto a;  // 错误,没有初始化表达式,无法推断出a的类型
// auto int a = 10; // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。
  
 // 1. 自动帮助推导类型
 auto a = 10;
 auto c = 'A';
 auto s("hello");
  
 // 2. 类型冗长
 map<int, map<int,int> > map_;
 map<int, map<int,int>>::const_iterator itr1 = map_.begin();
 constauto itr2 = map_.begin();
 auto ptr = []()
 {
 std::cout << "hello world" << std::endl;
 };
  
 return0;
};
  
// 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,
// 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。
template<classT,classU>
voidMultiply(T t, U u)
{
 auto v = t * u;
}

二、返回值占位

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

三、使用注意事项

1、我们可以使用valatilepointer(*) ,reference(&) ,rvalue reference(&&) 来修饰auto

?
1
2
3
4
auto k = 5;
auto* pK = newauto(k);
auto** ppK = newauto(&k);
constauto n = 6;

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

?
1
auto m; // m should be intialized

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

?
1
autointp;// 这是旧auto的做法。

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

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

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

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

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

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

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

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

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

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

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

?
1
2
3
4
5
6
inta[9];
auto j = a;
cout<<typeid(j).name()<<endl;// This will print int*
  
auto& k = a;
cout<<typeid(k).name()<<endl;// This will print int [9]


原创粉丝点击