问题
Is there any way to achieve undefined behavior in Rust without using unsafe
?
Of course, such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one.
回答1:
Absolutely, but any such case is a bug with Rust or the standard libary.
My favorite example is LLVM loop optimization can make safe programs crash, which actually occurs due to a poor interaction of Rust and LLVM semantics:
pub fn oops() {
(|| loop {
drop(42)
})()
}
Compiled with optimizations on Rust 1.49.0, this produces the assembly:
playground::oops:
ud2
such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one
The standard library is a "third-party library", so I don't get the distinction.
来源:https://stackoverflow.com/questions/62559509/is-undefined-behavior-possible-in-safe-rust