又一次试图阅读并理解《Effective C++》

条款01:视C++为一个语言联邦

C++:

  • C
  • C++面向对象
  • template 泛型编程
  • STL

条款02:尽量以constenuminline替换#define

即让预处理的活尽量转移给编译器

指针

1
const char* const str [] ="effective c plus plus";

定义为string更好

1
const std::string str("effective c plus plus");

相对于define不重视作用域,const可以在类中修饰类的成员

enum hack

一个属于枚举类型的变量可以被当做int使用

优秀的编译器不会为 整数类型常量分配另外的存储空间(除非创建指针或者引用指向这个变量),但是并非所有编译器都是如此,enum hack类似于define,二者都不可以取地址,可以阻止取地址这种行为

宏定义函数

转换为template inline 函数

1
#define CALL_WITH_MAX(a,b) f((a)>(b) ? (a) : (b))

转换为

1
2
3
4
5
template<typename T>
inline void callWithMax(const T& a,const T& b)
{
f(a>b ? a:b);
}

条款03:尽可能使用const

只要某值不变是事实,就应该使用const,从而获得编译器的帮助,建立约束

对于编译器,constphysical,但是我们书写代码应该保证是logical

指针

函数

成员函数