当前位置: 首页 > news >正文

auto自动类型推导总结

auto 自动推导的规则很多、很细,当涉及移动语义、模板等复杂的规则时,很容易绕进去。因此,在使用 auto 进行自动推导时,牢记以下几点:

  • auto 推导出的是 “值类型”,不会是 “引用类型”。
  • auto 可以和 const、& 这些类型修饰符结合,得到新的类型;在自动推导时,先不考虑额外的修饰,看看推导出的是什么类型,然后再加上修饰符。
  • 类成员变量初始化时,不允许使用 auto 推到类型。

普通类型推导

auto p = new int(20);   // p 的类型为 int*auto str1 = "hello";     // str1 的类型C风格字符串 const char*,至于为什么是const,很好理解,"hello" 是字面值即常量auto str2 = "hello"s;    // str2 的类型为 string,需要打开名字空间 using namespace std::literals::string_literals(C++14及之后)auto str3 = std::string("hello");auto r = &str2;     // string*auto i = 1;     // intauto l = 2L;    // longauto ll = 3LL;  // long longauto f = 1.23f; // floatauto d = 3.1415926535;  // doubleauto vec_init = {1, 2, 3, 4, 5};        // std::initializer_list<int>auto vec = std::vector<int>{1, 2, 3, 4, 5};     // std::initializer_list<int>
}

和 const、volatile、*、& 结合

与 const 结合

const auto i = 10;          // const int
const auto f = 0.23f;       // const float
const auto d = 1.234345;    // const doubleconst auto s = std::string("hello");    // const stringconst auto vec_init = {1, 2, 3, 4, 5};        // std::initializer_list<int>
const auto vec = std::vector<int>{1, 2, 3, 4, 5};     // std::initializer_list<int>auto ch = "hello";          // const char *
const auto chr = "hello";   // const char *const

一个需要注意的点是,当使用字符串字面值推导时,推导出的时 const char * ,而当与 const 结合时,推导出的是 const char *const

与 & 结合

auto 根据表达式的结果推导变量类型,推导的是值类型。因此若希望推导的是引用类型,则需要和 & 结合。

auto i = 10;    // int
auto &ri = i;   // int&auto &r = 10;   // 错误,r被推导出 int&,而左值引用不能绑定右值auto &&r = 10;  // 正确,rr被推导出 int&&,右值引用只能绑定右值
int getInt() {int num = 1;return num;
}auto i = getInt();      // int
auto &r = getInt();     // 错误,getInt()返回的是将亡对象,是右值
auto &&rr = getInt();   // 正确,int&&,右值引用绑定到右值

待补充。。。(2023年10月23日)

http://www.lryc.cn/news/213291.html

相关文章:

  • 透视2023,如何看清中国SaaS的未来之路?
  • 分类预测 | Matlab实现KOA-CNN-LSTM-selfAttention多特征分类预测(自注意力机制)
  • 博客系统-项目测试
  • Inspeckage,动态分析安卓 APP 的 Xposed 模块
  • Windows详细安装和彻底删除RabbitMQ图文流程
  • 自定义表单规则
  • Spring 中 Bean 的作用域有哪些?Spring 中有哪些方式可以把 Bean 注入到 IOC 容器?
  • 【01低功耗蓝牙开发】
  • 【Java 进阶篇】Java BeanUtils 使用详解
  • YugaByteDB -- 全新的 “PostgreSQL“ 存储层
  • 众佰诚:抖音上做生意卖什么好
  • 【Redis】环境配置
  • 设计交换机原理图前应先理清的框图
  • Bellman-ford 贝尔曼-福特算法
  • Docker数据目录迁移解决方案
  • 公共字段自动填充、菜品管理
  • 前端面试 面试多起来了
  • Qt常见类名关系整理
  • YOLO8实战:yolov8实现行人跟踪计数
  • shell脚本学习-2
  • web3:智能合约浏览器版本的 IDE - remix 使用教程
  • 信号类型(通信)——QPSK、OQPSK、IJF_OQPSK调制信号
  • 常用压缩文件操作函数总结
  • leetcode_274 H指数
  • 微服务框架Consul--新手入门
  • docker运行syslog-ng,搭建日志服务器
  • Redis代替session实现用户验证
  • Ubuntu 内核降级到指定版本
  • uniapp开发app,在ios真机上出现的css样式问题
  • uniapp 页面间传参方法