ES.103: Don't overflow
ES.103:防止溢出
Reason(原因)
Overflow usually makes your numeric algorithm meaningless. Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
溢出通常会导致数字算法失去意义。超过最大值的增量运算会导致内存破坏和无定义的行为。
Example, bad(反面示例)
代码语言:javascript复制int a[10];
a[10] = 7; // bad
int n = 0;
while (n < 10)
a[n - 1] = 9; // bad (twice)
Example, bad(反面示例)
代码语言:javascript复制int n = numeric_limits<int>::max();
int m = n 1; // bad
Example, bad(反面示例)
代码语言:javascript复制int area(int h, int w) { return h * w; }
auto a = area(10'000'000, 100'000'000); // bad
Exception(例外)
Use unsigned types if you really want modulo arithmetic.
如果你确实需要按模运算可以使用无符号类型。
Alternative: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
可选项:对于可以承受一定额外开销的敏感应用,使用带有范围检查的整数或者浮点数。
Enforcement(实施建议)
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es103-dont-overflow