農林漁牧網

您現在的位置是:首頁 > 農業

C++核心準則ES.103​:防止溢位​

2021-11-28由 面向物件思考 發表于 農業

移碼運算怎麼避免發生溢位

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。

溢位通常會導致數字演算法失去意義。超過最大值的增量運算會導致記憶體破壞和無定義的行為。

Example, bad(反面示例)

int a[10];a[10] = 7; // badint 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); // 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

覺得本文有幫助?請分享給更多人。

關注微信公眾號【面向物件思考】輕鬆學習每一天!

面向物件開發,面向物件思考!