在C语言中,就有了auto关键字,它被当作是一个变量的存储类型修饰符,表示自动变量(局部变量)。它不能被单独使用,否则编译器会给出警告。在C++11标准中,添加了新的类型推导特性。在C ++11中,使用auto定义的变量不能使用其它类型修饰符修饰,该变量的类型由编译器根据初始化数据自动确定。

C++中类型检查是在编译阶段。动态类型语言能做到在运行时决定类型,主要归功于一技术,这技术是类型推导。在C++11中,可以通过重定义auto关键字来实现类型推导。

在C++11中,使用auto关键字可以要求编译器对变量的类型进行自动推导。

auto关键字:类型推导,从该关键字的初始化表达式中推导变量的类型。

在块作用域、命名空间作用域、for循环的初始化语句内声明变量的时候,变量的类型可以被省略,使用关键字auto来代替。

auto声明的变量必须被初始化,以使编译器能够从其初始化表达式中推导出其类型。

声明为auto的变量在编译时期就分配了内存,而不是到了运行时期,所以使用auto不再引发任何速度延迟,这也意味着使用auto的时候,这个变量不初始化会报错,因为编译器无法知道这个变量的类型。

auto使用时需注意:

(1)、可以使用const、volatile、pointer(*)、reference(&)、rvalue reference(&&)等说明符和声明符来修饰auto关键字;

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

(3)、auto不能与其它任何类型说明符一起使用;

(4)、方法、参数或模板参数不能被声明为auto;

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

(6)、auto是一个占位符,不是类型,不能用于类型转换或其它一些操作,如sizeof、typeid;

(7)、auto关键字内声明的声明符列表的所有符号必须解析为同一类型;

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

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

(10)、auto不能作为函数的返回类型,在C++14中是可以的。

建议:大多数情况使用关键字auto,除非非常需要转换。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "auto.hpp"
#include <iostream>
#include <cmath>
#include <typeinfo>
#include <string>
#include <map>
#include <list>
#include <deque>
#include <vector>//
// reference: http://en.cppreference.com/w/cpp/language/auto
template<class T, class U>
auto add(T t, U u) -> decltype(t + u) // the return type is the type of operator+(T, U)
{return t + u;
}auto get_fun(int arg) -> double(*)(double) // same as: double (*get_fun(int))(double)
{switch (arg) {case 1: return std::fabs;case 2: return std::sin;default: return std::cos;}
}int test_auto1()
{auto a = 1 + 2;std::cout << "type of a: " << typeid(a).name() << '\n'; // type of a: intauto b = add(1, 1.2);std::cout << "type of b: " << typeid(b).name() << '\n'; // type of b: doubleauto c = { 1, 2 };std::cout << "type of c: " << typeid(c).name() << '\n'; // type of c: class std::initializer_list<int>auto my_lambda = [](int x) { return x + 3; };std::cout << "my_lambda: " << my_lambda(5) << '\n'; // my_lambda: 8auto my_fun = get_fun(2);std::cout << "type of my_fun: " << typeid(my_fun).name() << '\n'; // type of my_fun: double (__cdecl*)(double)std::cout << "my_fun: " << my_fun(3) << '\n'; // my_fun: 0.14112// auto int x; // error as of C++11: "auto" is no longer a storage-class specifier // error C3530: “auto”不能与任何其他类型说明符组合return 0;
}// reference: https://msdn.microsoft.com/zh-cn/library/dd293667(v=vs.120).aspx
int f(int x) { return x; }int test_auto2()
{int count = 10;int& countRef = count;auto myAuto = countRef;countRef = 11;std::cout << count << " " << std::endl; // 11myAuto = 12;std::cout << count << std::endl; // 11// 1. 下面的声明等效。 在第一个语句中,声明 j 变量为类型 int。 在第二个语句,因为初始化表达式 (0) 是整数,所以变量 k 推导为 int 类型int j = 0;  // Variable j is explicitly type int.auto k = 0; // Variable k is implicitly type int because 0 is an integer.// 2. 以下声明等效,但第二个声明比第一个简单std::map<int, std::list<std::string>> m;std::map<int, std::list<std::string>>::iterator i = m.begin();auto i_ = m.begin();// 3. 声明 iter 和 elem 变量类型std::deque<double> dqDoubleData(10, 0.1);for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter) { /* ... */}// prefer range-for loops with the following information in mind// (this applies to any range-for with auto, not just deque)for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples { /* ... */ }for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE{ /* ... */ }for (const auto& elem : dqDoubleData) // observes elements IN-PLACE{ /* ... */ }// 4. 使用 new 运算符double x = 12.34;auto *y = new auto(x), **z = new auto(&x);// 5. 所有符号解析为同一类型auto x_ = 1, *y_ = &x_, **z_ = &y_; // Resolves to int.auto a(2.01), *b(&a);         // Resolves to double.auto c = 'a', *d(&c);          // Resolves to char.auto m_ = 1, &n_ = m_;            // Resolves to int.// 6. 使用条件运算符 (?:)int v1 = 100, v2 = 200;auto e = v1 > v2 ? v1 : v2;// 7. 将变量 x7 初始化类型 int,将引用的变量 y7 初始化为类型 const int,及将变量 fp 初始化为指向返回类型 int 的函数的指针auto x7 = f(0);const auto & y7 = f(1);int(*p)(int x7);p = f;auto fp = p;return 0;
}/
// reference: http://www.learncpp.com/cpp-tutorial/4-8-the-auto-keyword/
int add_3(int x, int y)
{return x + y;
}int test_auto3()
{auto d = 5.0; // 5.0 is a double literal, so d will be type doubleauto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type intauto sum = add_3(5, 6); // add_3() returns an int, so sum will be type intreturn 0;
}

GitHub:https://github.com/fengbingchun/Messy_Test

C++11中auto的使用相关推荐

  1. reference to ‘count’ is ambiguous报错解决以及C++11中auto自动变量

    记录一下排坑过程(C++报错 reference to 'count' is ambiguous): 涉及到#命名空间的知识点,以及一些C++11新标准(auto)的记录,只想解决同类问题的小伙伴可以 ...

  2. C++11 中的内联函数、auto关键字、for循环及空指针

    C++ 3 内联函数 概念 特性 auto关键字 定义 使用 auto与指针结合起来使用 在同一行定义多个变量 auto不能推导的场景 auto不能作为函数的参数 auto不能直接用来声明数组 基于范 ...

  3. C++11中std::async的使用

    C++11中的std::async是个模板函数.std::async异步调用函数,在某个时候以Args作为参数(可变长参数)调用Fn,无需等待Fn执行完成就可返回,返回结果是个std::future对 ...

  4. C++11中std::packaged_task的使用

    C++11中的std::packaged_task是个模板类.std::packaged_task包装任何可调用目标(函数.lambda表达式.bind表达式.函数对象)以便它可以被异步调用.它的返回 ...

  5. C++11中std::shared_future的使用

    C++11中的std::shared_future是个模板类.与std::future类似,std::shared_future提供了一种访问异步操作结果的机制:不同于std::future,std: ...

  6. C++11中std::future的使用

    C++11中的std::future是一个模板类.std::future提供了一种用于访问异步操作结果的机制.std::future所引用的共享状态不能与任何其它异步返回的对象共享(与std::sha ...

  7. C++/C++11中用于定义类型别名的两种方法:typedef和using

    类型别名(type alias)是一个名字,它是某种类型的同义词.使用类型别名有很多好处,它让复杂的类型名字变得简单明了.易于理解和使用,还有助于程序员清楚地知道使用该类型的真实目的.在C++中,任何 ...

  8. C++/C++11中头文件functional的使用

    <functional>是C++标准库中的一个头文件,定义了C++标准中多个用于表示函数对象(function object)的类模板,包括算法操作.比较操作.逻辑操作:以及用于绑定函数对 ...

  9. 概率论中指数分布介绍及C++11中std::exponential_distribution的使用

    指数分布:在深度学习中,我们经常会需要一个在x=0点处取得边界点(sharp point)的分布.为了实现这一目的,我们可以使用指数分布(exponential distribution): p(x; ...

最新文章

  1. android studio修改项目包名
  2. 成功解决.append方法出现错误IndexError: list index out of range
  3. 直播 | AAAI 2021:文本对抗攻防中的对抗训练方法
  4. 记一次 .NET 车联网云端服务 CPU爆高分析
  5. Android动态图标包制作教程,安卓手机ico图标制作美化图文教程
  6. Notes of fwt
  7. 如何在Delphi 中调用C#生成的DLL类库
  8. yii2基础之modal弹窗的基本使用
  9. springmvc配置拦截器
  10. 汉高澳大利亚sinox2014电影播放flash最好的办法是安装游戏windows文本firefox
  11. SQLite学习笔记(二)--VC调用环境搭建
  12. win10系统steam登陆计算机授权,steam登陆授权
  13. 魔兽世界怀旧服哪个服务器金价稳定,魔兽世界怀旧服 金价到底会跌到多少的分析...
  14. 跑语义分割程序时报错
  15. java获得指定时间的前几天或后几天是哪一天
  16. [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
  17. c#rs232与三菱通讯_C#对三菱PLC的以太网和串口通讯以及台达PLC的以太网通讯
  18. 深入讲解WebView
  19. 技术人员,不要让情商成为你的短板
  20. 数字化生存时代来临:谁能重组互联网下半场的信息 DNA?

热门文章

  1. 【camera-radar】基于ROS的多传感器融合感知系统实现(雷达+相机)(3)
  2. 深度学习--TensorFlow(4)BP神经网络(损失函数、梯度下降、常用激活函数、梯度消失梯度爆炸)
  3. 【神经网络】(17) EfficientNet 代码复现,网络解析,附Tensorflow完整代码
  4. 计算机图形学——三角形网格
  5. 个人建议:设置Alt+S快捷键来控制VSCode自动保存切换功能
  6. 实现第一个自定义nginx模块
  7. 从 SSLTLS 的底层实现来看 网络安全的庞大复杂体系
  8. Rocksdb 通过ingestfile 来支持高效的离线数据导入
  9. 【MySQL解惑笔记】忘记MySQL数据库密码
  10. 使用nmonchart把.nmon文件转换成html