<Effective Mordern C++>Item 6:UseTheExplicitlyTypedInitializerIdiomWhenAutoDeducesUndesiredTypes
来源:互联网 发布:ubuntu tty1 登录 编辑:程序博客网 时间:2024/05/23 21:59
啊…别人总结的精简干练,那么…再怒转一篇???
原博
在Item5中提到了使用auto
所带来的诸多优点,在Item2中提到了auto的类型推导规则和模板类型推导基本一致,推导出来的类型有的时候并不是我们所想要的类型(会忽略CV限制符和引用),那么本文继续探究auto的其它缺点。
std::vector<bool> features();auto ret = features();
上面的ret是bool类型吗? 表面看起来是没什么问题的,其实不然,vector<bool>
的operator[]
的返回值其实并不是bool类型,vector<bool>
比较特殊,它返回的是vector<bool>::reference
,返回一个bool
引用类型不就完了嘛,标准库干嘛非要这么大费周章的搞了个这样的类型呢?,原因有以下几个:
- 因为bool占用一个字节,标准库为了节省内存,改用bit来表示
- 因为operator[]需要返回一个内部元素的引用,但是没办法对一个bit进行引用
- 为了让返回的类型统一,无论是bool类型,还是其它类型
为此标准库为了实现上述三个目标就封装了一个内部的类型vector<bool>::reference
,因此auto在这里老老实实得到了一个vector<bool>::reference
类型,而如果使用下面的代码:
bool ret = features();
features返回的vector<bool>::reference
类型会隐式转换为bool类型。
在这个场景下auto弄巧成拙,幸好我们可以通过使用static_cast强制进行类型转换得到我们想要的类型。(static_cast可以用来去引用)
auto ret = static_cast<bool>(features);
0 0
- <Effective Mordern C++>Item 6:UseTheExplicitlyTypedInitializerIdiomWhenAutoDeducesUndesiredTypes
- <Effective Mordern C++>笔记:Item 2:Understand auto type deduction.
- <Effective Mordern C++>笔记:Item 3:Understand decltype .
- <Effective Mordern C++>笔记:Item 1: Understand the template type deduction.
- <Effective Mordern C++>笔记:Item 4:Knowing how to view deduced types .
- <Effective Mordern C++>笔记:Item 5:Prefer auto to explicit type declarations.
- <Effective Mordern C++>笔记:Item 7:Distinguish () and {} when creating objs.
- <Effective Mordern C++>笔记:Item 8:prefer nullptr to 0 and NULL.
- <Effective Mordern C++>笔记:Item 9:prefer alias declarations to typedefs.
- More Effective C++:Item 27
- More Effective C++:Item 27
- effective stl item 6
- 《Effective C#》Item 6:区分值类型和引用类型
- 《Effective C#》Item 6:区分值类型和引用类型
- Effective Objective-C 2.0: Item 6: Understand Properties
- read Item 25 of《More Effective C++》
- 《Effective Modern C++》Item 1总结
- 《Effective Modern C++》Item 2总结
- Leetcode学习(16)—— Max Consecutive Ones
- PHP 使用MYSQLI扩展操作数据库
- 线程视图(并行性能)
- 内部排序
- 欢迎使用CSDN-markdown编辑器
- <Effective Mordern C++>Item 6:UseTheExplicitlyTypedInitializerIdiomWhenAutoDeducesUndesiredTypes
- [leetcode]: 350. Intersection of Two Arrays II
- PHP mysqli 预处理
- ionic入门之数据绑定显示-1
- matlab 内存不足
- 未来生活进行时: 畅想未来新兴技术40年——百大趋势性技术汇总(中)
- Java-String类的常用方法总结
- “涪气”满满 中国页岩气开发驶入“快车道”
- css 坑