C++中什么时候发生隐式类型转换?

When does implicit type conversion occur in C++?

假设我们有以下代码,旨在将 a 的位向左移动 i 并将 ai LSB 替换为i b

的 MSB
unsigned short a;
unsigned short b;
auto i = 4;

a = (a << i) | (b >> (16 - i));

这按预期工作。现在,让我们考虑一下我们希望能够对 对不同类型执行此操作的情况。 即我们希望将 a 的位向左移动 i 并将 ai LSB 替换为 bi MSB,除了现在我们无法保证 ab,只是它们是无符号的。让我们考虑 a 的大小小于 b

的情况
unsigned short a;
unsigned int b;
auto i = 4;

a = (a << i) | (b >> (32- i));

我很担心“overshiftinga。但是,根据从 a 提升到 unsigned int 的时间,值可能是也可能不是超移。考虑 i=24 的值。如果类型转换发生在转换之后而不是之前,这将导致未定义的行为。因此,我的问题是这种情况下什么时候会发生类型转换?我想我可以明确地将 a 转换为更大的类型,但我想尽可能避免这种情况。

这是标准中的相关引述,[expr.shift/1]:

[...] The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. [...]

这意味着在您的情况下 a 将被提升为 int(或 unsigned int 进行轮班之前。

请注意,对于当前的 32/64 位编译器,提升的类型是 int,而不是 unsigned int。仅当 int 不能表示 unsigned short 的整个范围时,提升的类型才为 unsigned int(例如,这对于旧的 16 位编译器是正确的,其中 sizeof(int) 是 2 , 和 sizeof(short)==sizeof(int)).