C++怎么避免有损算数转换

本篇内容介绍了“C++怎么避免有损算数转换”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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

准则支持库提供了一个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(实施建议)

实现良好的代码分析器可以检出所有的窄化转换。但是标识所有的窄化转换会导致大量的假阳性结果。建议:

  • 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.

  • 函数参数的窄化转换尤其可疑。


“C++怎么避免有损算数转换”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!