ES.103: Don't overflow
ES.103:防止溢出
Overflow usually makes your numeric algorithm meaningless. Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
溢出通常会导致数字算法失去意义。超过最大值的增量运算会导致内存破坏和无定义的行为。
Example, bad(反面示例)
int a[10];
a[10] = 7; // bad
int n = 0;
while (n++ < 10)
a[n - 1] = 9; // bad (twice)
int n = numeric_limits<int>::max();
int m = n + 1; // bad
int area(int h, int w) { return h * w; }
auto a = area(10'000'000, 100'000'000); // bad
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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有