[Solved] Creates a temporary which is freed while still in use

#1

Hi guys! I am trying to find every c++ file in every folder / subfolder and add it into an Array.
But it throws error:
creates a temporary which is freed while still in use.

code: Error + Code

0 Likes

#2

With the code you have, you need to keep the String that’s returned by to_string() in a binding, i.e.:

let p = e.path().display().to_string();

if get_extension_from_filename(&p) == Some("cpp") {
    cpp_files.push(p);
}

But you probably want to work with the Path API a bit more, rather than strings. Something like (untested):

for e in WalkDir::new(".").into_iter().filter_map(|e| e.ok()) {
        if e.metadata().unwrap().is_file() {
            if e.path().extension() == Some(OsStr::new("cpp")) {
                // into_path() gives you a (owned) `PathBuf`
                cpp_files.push(e.into_path());
            }
        }
}
3 Likes

#3

Hi and thank you for your answer! I solved it with .clone();
let p = e.path().display().to_string().clone();

0 Likes