Skip to content

Commit ab7b743

Browse files
committedJun 26, 2016
Update Items 5~6
1 parent 0bf2167 commit ab7b743

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 

‎2016/1.markdown

+25
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
## 1. Effective Modern C++
2+
23
### Deduce Types
34
+ Item 1: Understand template type deduction
45
+ 形参声明的推导结果:
@@ -28,9 +29,32 @@
2829
+ `typeid(T).name()` 是不行的:
2930
1. `name()`不保证可读,不同编译器下的实现不同。clang/gcc可读性较差,msvc的可读性较好。
3031
2. 标准规定,typeid的形参声明相当于T,所以不能反映实参的类型。
32+
3133
### Auto
3234
+ Item 5: Prefer auto to explicit type declartions
35+
+ auto 的优点:
36+
+ 对重构友好
37+
+ 必须初始化
38+
+ 简化声明,比如迭代器。
39+
+ 能够声明只有编译器知道的类型,比如lambda表达式
40+
+ 使用auto来声明lambda表达式相比用`function<xxx>` 的优点:
41+
+ 避免了`function<xxx>` 的多态开销,比如内部的对分配
42+
+ 每个lambda可以有独立的类型,传值给模板函数时,可以实例化出专有的函数实现,从而允许内联
43+
+ 可以声明泛型lambda
44+
+ 能够声明准确的类型,避免常见的类型陷阱
45+
+ `unsigned size = vec.size()`,不可移植,64bit下溢出
46+
+ `for (const pair<string, int> &p : map)`,其实发生了隐式类型转换`pair<string const, int> -> pair<string, int>`,因此p其实引用的是一个右值
47+
+ 关于auto影响可读性的讨论
48+
+ auto不是强制的,你可以在有必要的时候显示声明
49+
+ auto不是c++独创的,已经在静态函数式语言和动态语言中广泛的使用
50+
+ 可以通过ide查看实际类型
51+
+ auto 的缺点
52+
+ {} 被返回值/lambda以外被推导成initializer_list,这和显示声明时结果不同
53+
+ 会将hidden proxy暴露出来,导致undefined bahvior,需要用户自己去发现hidden proxy。比如`bool x = getBoolVector()[0];` 是ok的,而`auto x = getBoolVector()[0]` 声明了一个bool的proxy,引用了一个右值的容器,非法。
3354
+ Item 6: Use the explicitly typed initializer idiom when auto deduceds undesired types
55+
+ 使用static_cast将hidden proxy实例转化成被代理的类型实例
56+
+ `auto x = static_cast<bool>(getBoolVector()[0])` 强调了这个转换的必要;而如果继续使用`bool x = getBoolVector()[0]`的话,一旦未来被人不小心refactor到auto,就break掉了,坑。
57+
3458
### Moving to Modern C++
3559
+ Item 7: Distinguish between () and {} when creating objects
3660
+ Item 8: Prefer nullptr to 0 and NULL
@@ -43,4 +67,5 @@
4367
+ Item 15: Use constexpr whenever possible
4468
+ Item 16: Make const member functions thread safe
4569
+ Item 17: Understand special member function generation
70+
4671
### Smart Pointers

0 commit comments

Comments
 (0)