Visual C 2017和
gcc 5.4生成从’const unsigned char’到’const float’的转换需要对B行进行缩小转换警告,但在此代码段中不需要对A行进行转换:
#include <iostream> int main() { const unsigned char p = 13; const float q = p; // Line A std::cout << q << '\n'; const unsigned char c[3] = {0,1,255}; const float f[3] = {c[2],c[0],c[1]}; // Line B for (auto x:f) std::cout << x << '\n'; }
这个警告有效吗?为什么B线的处理方式与A线不同?
解决方法
警告有效,aggregate initialization禁止C 11
narrowing conversions;但未在
copy initialization中应用(如前所述).
If the initializer clause is an expression,implicit conversions are allowed as per copy-initialization
,except if they are narrowing (as in list-initialization) (since C++11).
Until C++11,narrowing conversions were permitted in aggregate initialization,but they are no longer allowed.
和
list-initialization limits the allowed implicit conversions by
prohibiting the following:
- conversion from an integer type to a floating-point type,except where the source is a constant expression whose value can be stored
exactly in the target type
BTW:c [0],c [1]和c [2]是not constant expressions;你可以将数组声明为constexpr,即constexpr unsigned char c [3] = {0,255};.然后应用异常,Line B也可以正常工作.