C++是一种强范例言语,声明变量时必需明确指出其范例。然则,在实践中,上风我们很难揣摸出某个表达式的值的范例,尤其是跟着模板范例的涌现,要想弄邃晓某些庞杂表达式的返回范例就变得越发难题。为了处理这个题目,C++11中引入的auto主要有两种用处:自动范例揣摸和返回值占位。auto在C++98中的标识暂时变量的语义,因为运用少少且过剩,在C++11中已被删除。前后两个规范的auto,完全是两个观点。
一、自动范例揣摸
auto自动范例揣摸,用于从初始化表达式中揣摸出变量的数据范例。经由过程auto的自动范例揣摸,能够大大简化我们的编程事情。下面是一些运用auto的例子。
#include <vector> #include <map> using namespace std; int main(int argc, 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(); const auto itr2 = map_.begin(); auto ptr = []() { std::cout << "hello world" << std::endl; }; return 0; }; // 3. 运用模板手艺时,假如某个变量的范例依赖于模板参数, // 不运用auto将很难肯定变量的范例(运用auto后,将由编译器自动举行肯定)。 template <class T, class U> void Multiply(T t, U u) { auto v = t * u; }
二、返回值占位
template <typename T1, typename T2> auto compose(T1 t1, T2 t2) -> decltype(t1 + t2) { return t1+t2; } auto v = compose(2, 3.14); // v's type is double
三、运用注意事项
1、我们能够运用valatile,pointer(*) ,reference(&) ,rvalue reference(&&) 来润饰auto
auto k = 5; auto* pK = new auto(k); auto** ppK = new auto(&k); const auto n = 6;
2、用auto声明的变量必需初始化
auto m; // m should be intialized
3、auto不能与其他范例组合连用
auto int p; // 这是旧auto的做法。
4、函数和模板参数不能被声明为auto
void MyFunction(auto parameter){} // no auto as method argument template<auto T> // utter nonsense - not allowed void Fun(T t){}
5、定义在堆上的变量,运用了auto的表达式必需被初始化
int* p = new auto(0); //fine int* pp = new auto(); // should be initialized auto x = new auto(); // Hmmm ... no intializer auto* y = new auto(9); // Fine. Here y is a int* auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)
6、认为auto是一个占位符,并非一个他本身的范例,因而不能用于范例转换或其他一些操纵,如sizeof和typeid
int value = 123; auto x2 = (auto)value; // no casting using auto auto x3 = static_cast<auto>(value); // same as above
7、定义在一个auto序列的变量必需一直推导成统一范例
auto x1 = 5, x2 = 5.0, x3='r'; // This is too much....we cannot combine like this
8、auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为援用范例
const int i = 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会退化成指向数组的指针,除非被声明为援用
int a[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]
总结
以上就是这篇文章的全部内容了,愿望本文的内容对人人进修或许运用C++能有肯定的协助,假如有疑问人人能够留言交换。
更多C++11新特征之auto的运用相干文章请关注ki4网!