原因
代码清晰和高效。你不需要对编译期捕获的错误写异常处理。
例子
// Int is an alias used for integers
int bits = 0; // don't: avoidable code
for (Int i = 1; i; i <<= 1)
++bits;
if (bits < 32)
cerr << "Int too small\n";
这个例子不能实现它想要的功能(因为溢出未定义),可以替换为简单的static_assert
:
// Int is an alias used for integers
static_assert(sizeof(Int) >= 4); // do: compile-time check
或者最好用类型系统把Int
替换为int32_t
。
例子
void read(int* p, int n); // read max n integers into *p
int a[100];
read(a, 1000); // bad, off the end
更好的写法:
void read(span<int> r); // read into the range of integers r
int a[100];
read(a); // better: let the compiler figure out the number of elements
替换原理
在编译期能做好的事情不要推迟到运行期
补充
- 寻找指针参数。
- 查找范围违规的运行时检查。