Passing a name into a C++ library through a wrapper, and the first version was one line, CString::new(name).unwrap().as_ptr(). rustc warned right away that the temporary CString dies at the end of the statement and the pointer will dangle. Fine, fair. So I moved it into a small function that builds the CString in a local and returns as_ptr(), and the warning went away, and I almost relaxed, and then it hit me that nothing changed, the string now just dies at the end of the function instead of the statement.
use std::ffi::{c_char, CString};
fn name_ptr(s: &str) -> *const c_char {
let c = CString::new(s).unwrap();
c.as_ptr()
}
That compiles without a single warning. The lint catches the temporary in one expression and not a bound local that leaves the function, even though the help text on the warning itself says binding inside the function isn't enough when the pointer is returned. And if the C++ side also stores the pointer rather than just reading it during the call, then even a variable in the caller isn't enough, and I don't know yet which one it does, there's barely any documentation. For now I'm keeping the CString in the wrapper struct next to the handle so they live the same length, and I'll see what people say.
