【C++11】新特性——auto的使用

C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。

1. 自动类型推断

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

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

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. template<auto T> // utter nonsense - not allowed
  3. void Fun(T t){}

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

  1. int* p = new auto(0); //fine
  2. int* pp = new auto(); // should be initialized
  3. auto x = new auto(); // Hmmm ... no intializer
  4. auto* y = new auto(9); // Fine. Here y is a int*
  5. 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. 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. // Now let us try to have reference
  5. auto& k = i;      // Now k is const int&
  6. k = 100;          // Error. k is constant
  7. // Similarly with volatile qualifer

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

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

【C++11】新特性——auto的使用的更多相关文章

  1. C++11新特性— auto 和 decltype 区别和联系

    一. auto简介 编程时候常常需要把表达式的值付给变量,需要在声明变量的时候清楚的知道变量是什么类型.然而做到这一点并非那么容易(特别是模板中),有时候根本做不到.为了解决这个问题,C++11新标准 ...

  2. C++11新特性总结 (二)

    1. 范围for语句 C++11 引入了一种更为简单的for语句,这种for语句可以很方便的遍历容器或其他序列的所有元素 vector<int> vec = {1,2,3,4,5,6}; ...

  3. C++11新特性总结 (一)

    1. 概述 最近在看C++ Primer5 刚好看到一半,总结一下C++11里面确实加了很多新东西,如果没有任何了解,别说自己写了,看别人写的代码估计都会有些吃力.C++ Primer5是学习C++1 ...

  4. C++ 11 新特性

    C++11新特性:          1.auto          2.nullptr          3.for          4.lambda表达式          5.override ...

  5. [转载] C++11新特性

    C++11标准发布已有一段时间了, 维基百科上有对C++11新标准的变化和C++11新特性介绍的文章. 我是一名C++程序员,非常想了解一下C++11. 英文版的维基百科看起来非常费劲,而中文版维基百 ...

  6. 在C++98基础上学习C++11新特性

    自己一直用的是C++98规范来编程,对于C++11只闻其名却没用过其特性.近期因为工作的需要,需要掌握C++11的一些特性,所以查阅了一些C++11资料.因为自己有C++98的基础,所以从C++98过 ...

  7. C++11新特性——range for

    很多编程语言都有range for语法功能,自C++11起,终于将这个重要功能加入C++标准中.range for语句,可以方便的遍历给定序列中的每个元素并对其执行某种操作. 1.基本语法 for(d ...

  8. C++11新特性之一——Lambda表达式

    C++11新特性总结可以参考:http://www.cnblogs.com/pzhfei/archive/2013/03/02/CPP_new_feature.html#section_6.8 C++ ...

  9. C++11新特性应用--实现延时求值(std::function和std::bind)

    说是延时求值,注意还是想搞一搞std::function和std::bind. 之前博客<C++11新特性之std::function>注意是std::function怎样实现回调函数. ...

随机推荐

  1. iSCSI 与 ceph

    SCSI  小型计算机系统接口(SCSI,Small Computer System Interface)是一种用于计算机及其周边设备之间(硬盘.软驱.光驱.打印机.扫描仪等)系统级接口的独立处理器标 ...

  2. 美发帮--android APP开发实战

    登陆界面,LinearLayout  ImageView  Button   用到了ImageView自动缩放,和自定义Button形状及State-Drawable,还用到了动画. 自定义控件之圆形 ...

  3. [转]Spring 注解总结

    原文地址:http://blog.csdn.net/wangshfa/article/details/9712379 一 注解优点?注解解决了什么问题,为什么要使用注解? 二 注解的来龙去脉(历史) ...

  4. Js 校验时间、比较时间 和转换时间格式

    function checkDate(obj){ var strDate = obj.value; var nowDate = new Date(); var a=/^(\d{1,4})(-|\/)( ...

  5. 系统间通信(10)——RPC的基本概念

    1.概述 经过了详细的信息格式.网络IO模型的讲解,并且通过JAVA RMI的讲解进行了预热.从这篇文章开始我们将进入这个系列博文的另一个重点知识体系的讲解:RPC.在后续的几篇文章中,我们首先讲解R ...

  6. Leetcode Odd Even Linked List

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note her ...

  7. bzoj3514Codechef MARCH14 GERALD07加强版

    #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...

  8. System.BadImageFormatException: 未能加载文件或程序集""或它的某一个依赖项。试图加载格式不正确的程序。

    解决方法: 1.更改程序集的生成目标平台为[Any CPU],或者针对平台进行编译. 项目右键->[属性]->[生成]->[生成目标平台] 2.尝试一下修改线程池设置为32位支持.

  9. python图形界面(GUI)设计

    不要问我为什么要用 python 来做这种事,我回到“高兴咋地”也不是不可以,总之好奇有没有好的解决方案.逛了一圈下来,总体上来说,python 图形界面有以下几个可行度比较高的解决方案. 1. py ...

  10. MACOS 答题器,界面跳转

    国内OSX开发的资料实在少,甚至连一本开发的书都找不到… 更无语的是,苹果自家的开发文档Sample Code不仅还停留在OC版本,还是MRC的… 在这样的情况下,OSX开发还真得靠“想象力”… 网上 ...