溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++怎么避免有損算數(shù)轉(zhuǎn)換

發(fā)布時(shí)間:2021-11-26 13:58:02 來(lái)源:億速云 閱讀:184 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“C++怎么避免有損算數(shù)轉(zhuǎn)換”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

ES.46:避免有損(窄化,截短)算數(shù)轉(zhuǎn)換

Reason(原因)

A narrowing conversion destroys information, often unexpectedly so.

窄化轉(zhuǎn)換破壞信息,通常不是期待的動(dòng)作。

Example, bad(反面示例)

A key example is basic narrowing:

主要的示例說(shuō)明窄化的基本情況:

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(注意)

準(zhǔn)則支持庫(kù)提供了一個(gè)narrow_cast操作,可以用來(lái)表明窄化是可接受的;一個(gè)narrow(“如果發(fā)生窄化轉(zhuǎn)換”)操作,它可以在丟失了任何信息時(shí)拋出異常。

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:

這兩個(gè)操作也可以處理有損算數(shù)轉(zhuǎn)換,例如從負(fù)浮點(diǎn)數(shù)轉(zhuǎn)換為無(wú)符號(hào)整數(shù)的情況。

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(實(shí)施建議)

實(shí)現(xiàn)良好的代碼分析器可以檢出所有的窄化轉(zhuǎn)換。但是標(biāo)識(shí)所有的窄化轉(zhuǎn)換會(huì)導(dǎo)致大量的假陽(yáng)性結(jié)果。建議:

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

  • 標(biāo)記所有浮點(diǎn)數(shù)到整數(shù)的轉(zhuǎn)換(或許只需要標(biāo)記float到char和double到int。 都有可能! 我們需要數(shù)據(jù))

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

  • 標(biāo)記所有l(wèi)ong到char的轉(zhuǎn)換(我懷疑int到char的轉(zhuǎn)換很普遍。都有可能! 我們需要數(shù)據(jù))

  • Consider narrowing conversions for function arguments especially suspect.

  • 函數(shù)參數(shù)的窄化轉(zhuǎn)換尤其可疑。


“C++怎么避免有損算數(shù)轉(zhuǎn)換”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI