以 x86 为目标时在 c++ 中进行算术移位的可靠性
Reliability of having arithmetic shift in c++ when targeting x86
所以根据 c++ 规范
The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has
an unsigned type or if E1 has a signed type and a non-negative value,
the value of the result is the integral part of the quotient of
E1/2^E2. If E1 has a signed type and a negative value, the resulting
value is implementation-defined.
所以它是实现定义的,但是如果我使用的是针对 x86 平台的无错误编译器,并且我使用带符号的类型右移,是否有任何理由怀疑我不会移入带符号的位? (x86显然支持算术移位)
不要混淆 "implementation defined" 和 "undefined"。 "Implementation defined" 的字面意思是 "the implementation must define it"。它不是随机的,甚至不是你应该通过实验来确定的东西。行为由实现定义,符合标准的实现将记录这些行为细节(因为不这样做本身就是不符合标准的)。除了实现错误,程序将忠实地展示其 C++ 实现定义的行为。
虽然您不能依赖任何关于未定义行为的信息,但您可以依赖实现定义的行为在给定的 C++ 实现中保持一致。但是,假设相同硬件的不同实现将以相同的方式定义这些细节,甚至相同实现的不同版本将以这种方式保持一致是不安全的。
所以根据 c++ 规范
The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
所以它是实现定义的,但是如果我使用的是针对 x86 平台的无错误编译器,并且我使用带符号的类型右移,是否有任何理由怀疑我不会移入带符号的位? (x86显然支持算术移位)
不要混淆 "implementation defined" 和 "undefined"。 "Implementation defined" 的字面意思是 "the implementation must define it"。它不是随机的,甚至不是你应该通过实验来确定的东西。行为由实现定义,符合标准的实现将记录这些行为细节(因为不这样做本身就是不符合标准的)。除了实现错误,程序将忠实地展示其 C++ 实现定义的行为。
虽然您不能依赖任何关于未定义行为的信息,但您可以依赖实现定义的行为在给定的 C++ 实现中保持一致。但是,假设相同硬件的不同实现将以相同的方式定义这些细节,甚至相同实现的不同版本将以这种方式保持一致是不安全的。