`borrow_as_ptr` false negative when borrowing a temporary literal
Summary
The borrow_as_ptr lint is emitted for borrowing a local variable as a raw pointer, but it is not emitted when the borrowed expression is a temporary literal.
Lint Name
borrow_as_ptr
Reproducer
the lint does not fire for m1, but does for m2
#[inline(never)]
pub fn m1() {
let _ptr = &42f32 as *const f32;
}
#[inline(never)]
pub fn m2() {
let tmp = 42f32;
let _ptr = &tmp as *const f32;
}
https://godbolt.org/z/xoPTzr6sx
Version
&raw const and ptr::addr_or can't be used on temporary values. Suggesting to add an additional local in order to avoid the cast is excessive.
&raw const can't be used on temporary values
I wonder why not, since it seems to work fine with the cast version (let _ptr = &42f32 as *const f32;).
It's called lifetime extension IIRC.
this could also be written as:
#[inline(never)]
pub fn m1() {
let ptr = std::ptr::from_ref(&42f32);
}
Related: https://github.com/rust-lang/rust-clippy/pull/16214
You can't use from_ref for this since it doesn't extend the lifetime. Technically you can in that specific case due to const promotion, but you can't in general with a temporary.