前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.103​:防止溢出​

C++核心准则ES.103​:防止溢出​

作者头像
面向对象思考
发布2020-06-17 19:10:49
3360
发布2020-06-17 19:10:49
举报

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Example, bad(反面示例)
      • Example, bad(反面示例)
        • Exception(例外)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档