让我们考虑一下将无符号短整数值(或任何其他无符号整数类型)的右N位置零的函数(它的可能实现之一)。可能的实现可能看起来像以下:左移位并丢弃位
template<unsigned int shift>
unsigned short zero_right(unsigned short arg) {
using type = unsigned short;
constexpr type mask = ~(type(0));
constexpr type right_zeros = mask << shift; // <-- error here
return arg & right_zeros;
}
int check() {
return zero_right<4>(16);
}
有了这个代码,我已经获得所有的编译器抱怨,以这种或那种方式,对可能的溢出。铛是最明确的一个,有以下明确的信息:
error: implicit conversion from 'int' to 'const type' (aka 'const unsigned short') changes value from 1048560 to 65520 [-Werror,-Wconstant-conversion]
此代码看起来明确界定,并明确为一天给我,但是当3个编译器抱怨,我变得很紧张。我在这里错过了什么吗?真的有机会发生腥吗?
P.S.虽然zeriong左侧X位的替代实现可能是受欢迎和有趣的,但这个问题的主要焦点是发布代码的有效性。
@TavianBarnes,它们不能被晋升为无符号的参数签署整数。 – SergeyA
不是你在问什么,但是你可能想要知道的东西(并且不要提防)是,如果你左移一个无符号整数'n'位,其中'n'>> =你转移的类型,那就是未定义的行为。 –
@SergeyA但这仍然是问题:'<<'的结果是int,不短。在分配前将'mask << shift'的结果转换回'type'使错误消失。 –