C++核心準則ES.103?:防止溢出?

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.
溢出通常會導致數(shù)字算法失去意義。超過最大值的增量運算會導致內(nèi)存破壞和無定義的行為。
Example, bad(反面示例)
int a[10];
a[10] = 7; // bad
int n = 0;
while (n++ < 10)
a[n - 1] = 9; // bad (twice)
Example, bad(反面示例)
int n = numeric_limits::max();
int m = n + 1; // bad
Example, bad(反面示例)
int area(int h, int w) { return h * w; }
auto a = area(10'000'000, 100'000'000); // badException(例外)
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.
可選項:對于可以承受一定額外開銷的敏感應用,使用帶有范圍檢查的整數(shù)或者浮點數(shù)。
Enforcement(實施建議)
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es103-dont-overflow
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
