ES.46:避免有损(窄化,截短)算数转换
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
}
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
A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
实现良好的代码分析器可以检出所有的窄化转换。但是标识所有的窄化转换会导致大量的假阳性结果。建议:
链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions