是否预计 Rust 中的位移太大是未定义的行为?
Is it expected that a too large bitshift is undefined behavior in Rust?
当您运行此代码时:
#![allow(exceeding_bitshifts)]
fn main() {
const NUMBER: u64 = 0b_10101010;
fn print_shift(i: u32) {
println!("{:b}", NUMBER >> i);
}
print_shift(65);
println!("{:b}", NUMBER >> 65);
}
您会看到,在编译时或 运行 时,移动一个值超过位长的数字的位会产生不同的行为。
这是正常行为吗?它记录在某处吗?这不在 list of documented undefined behavior.
不,这不是预期的,但不是未定义的行为。 This is "just" a bug.
应该在编译时如何计算常量和在运行时如何计算值之间没有区别。这通常是一个难题,因为执行编译的机器和 运行 代码的机器可能具有完全不同的体系结构。
在谈论调试版本与发布版本时,"too large" 移位的行为是预期的,而且 不是未定义的行为。线索在错误信息中:
attempt to shift right with overflow
Integer overflow is neither unsafe nor undefined:
The Rust compiler does not consider the following behaviors unsafe,
though a programmer may (should) find them undesirable, unexpected, or
erroneous.
- ...
- Integer overflow
另请参阅:
当您运行此代码时:
#![allow(exceeding_bitshifts)]
fn main() {
const NUMBER: u64 = 0b_10101010;
fn print_shift(i: u32) {
println!("{:b}", NUMBER >> i);
}
print_shift(65);
println!("{:b}", NUMBER >> 65);
}
您会看到,在编译时或 运行 时,移动一个值超过位长的数字的位会产生不同的行为。
这是正常行为吗?它记录在某处吗?这不在 list of documented undefined behavior.
不,这不是预期的,但不是未定义的行为。 This is "just" a bug.
应该在编译时如何计算常量和在运行时如何计算值之间没有区别。这通常是一个难题,因为执行编译的机器和 运行 代码的机器可能具有完全不同的体系结构。
在谈论调试版本与发布版本时,"too large" 移位的行为是预期的,而且 不是未定义的行为。线索在错误信息中:
attempt to shift right with overflow
Integer overflow is neither unsafe nor undefined:
The Rust compiler does not consider the following behaviors unsafe, though a programmer may (should) find them undesirable, unexpected, or erroneous.
- ...
- Integer overflow
另请参阅: