Open
Description
What it does
The borrow checker prevents users from borrowing content from temporaries.
The following code...
fn mistake() {
let hello = String::from("hello").as_str();
hello.to_string();
}
gives this compiler error:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:17
|
4 | let hello = String::from("hello").as_str();
| ^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
5 | hello.to_string();
| ----- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
However, the same mistakes with raw pointers is not caught. This is almost always a mistake which can lead to use after free.
Luckily, most standard library APIs are designed to not make this mistake possible, but for some like CString::as_raw
there is already a clippy lint.
However, for custom smart pointer types, this issue is not caught by clippy (although it is caught by miri).
Categories (optional)
- Kind:
clippy::correctness
What is the advantage of the recommended code over the original code
The use of a pointer to a temporary is almost guaranteed to be incorrect.
Drawbacks
None.