C++核心準則ES.46:避免有損(窄化,截短)算數轉換

ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions

ES.46:避免有損(窄化,截短)算數轉換

 

Reason(原因)

A narrowing conversion destroys information, often unexpectedly so.

窄化轉換破壞信息,通常不是期待的動作。

 

Example, bad(反面示例)

A key example is basic narrowing:

主要的示例說明窄化的基本情況:

double d = 7.9;
int i = d;    // bad: narrowing: i becomes 7
i = (int) d;  // bad: we're going to claim this is still not explicit enough

void f(int x, long y, double d)
{
    char c1 = x;   // bad: narrowing
    char c2 = y;   // bad: narrowing
    char c3 = d;   // bad: narrowing
}

Note(注意)

The guidelines support library offers a narrow_cast operation for specifying that narrowing is acceptable and a narrow ("narrow if") that throws an exception if a narrowing would throw away information:

準則支持庫提供了一個narrow_cast操作,可以用來表明窄化是可接受的;一個narrow(“如果發生窄化轉換”)操作,它可以在丟失了任何信息時拋出異常。

i = narrow_cast<int>(d);   // OK (you asked for it): narrowing: i becomes 7
i = narrow<int>(d);        // OK: throws narrowing_error

We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:

這兩個操作也可以處理有損算數轉換,例如從負浮點數轉換爲無符號整數的情況。

double d = -7.9;
unsigned u = 0;

u = d;                          // BAD
u = narrow_cast<unsigned>(d);   // OK (you asked for it): u becomes 4294967289
u = narrow<unsigned>(d);        // OK: throws narrowing_error

Enforcement(實施建議)

A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:

實現良好的代碼分析器可以檢出所有的窄化轉換。但是標識所有的窄化轉換會導致大量的假陽性結果。建議:

  • Flag all floating-point to integer conversions (maybe only float->char and double->int. Here be dragons! we need data).

  • 標記所有浮點數到整數的轉換(或許只需要標記float到char和double到int。 都有可能! 我們需要數據)

  • Flag all long->char (I suspect int->char is very common. Here be dragons! we need data).

  • 標記所有long到char的轉換(我懷疑int到char的轉換很普遍。都有可能! 我們需要數據)

  • Consider narrowing conversions for function arguments especially suspect.

  • 函數參數的窄化轉換尤其可疑。

     

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章