KEY WORD¶
explicit¶
要求显示构造的,不能隐式传入参数, 防止例如整数和 Enum
转换。 可以避免一些隐式转换造成的BUG
inline¶
- 可以将值/函数的定义放在头文件,被重复包含(include), 而不会产生重复定义的编译错误。编译器会在多个cpp编译单元的实例中随机选择一个作为最终的定义
C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14
foo.h inline void hello(){ /*nothing*/ } void no_hello() {/*nothing*/ } --- bar.cpp #include "foo.h" int a =0; -- wtf.cpp #include "foo.h" int a =0;
Bash 1 2
g++ bar.cpp wtf.cpp # The `a` and no_hello will be a compile error
- 谣言: 加上此关键字后,函数就会被就地展开。
- 需要
__FORCE_INLINE__
或者gcc::always_inline
之类的编译器
方言/Attribute 来达到想象中的功能 - 编译器会智能的根据你的函数的行数,使用次数来进行就地展开(优化), 前提是编译器 "看见了" 你的函数实现
- 需要
const¶
- 即无法改变的意思(一定程度内)
C++ 1 2 3 4 5
int const a = 0; a = 2; // wrong!! int * b = const_cast<int *> (&a); *b = 2; // UB!! (也许被优化成编译器常量)
- 如何理解 const int* | int *const | const int *const
const
在*
之前没有区别const int *
与int * const
const int *const
static¶
-
让变量只能在当前文件使用,在其他文件 extern 无法引用
C++ 1 2 3 4 5 6 7 8
main.cc static int val; --- utils.cc // 编译后utils.cc 中val变量无法查找到 extern int val;
-
可以直接调用类的静态函数,而不用生成一个实例
- Notice: 在头文件的全局区域定义一个 static 变量/函数 可能是未定义行为 (被多个cpp包含,且彼此隔离)