Issue 128705
Summary [clang-tidy] Check request: bugprone-avoid-dangling-in-std-filesystem
Labels clang-tidy
Assignees
Reporter denzor200
    
Needs a check that will find usage of invalidated references to something that was owned by `std::filesystem::directory_iterator` before the invalidation. Since `std::filesystem::directory_iterator`'s increment has to invalidate all copies of the previous value of `*this`(look at https://en.cppreference.com/w/cpp/filesystem/directory_iterator/increment ), this check will suggest to make a copy instead of taking a reference.

BEFORE
```
namespace fs = std::filesystem;
fs::directory_iterator it("sandbox");
fs::directory_iterator end;
while (it != end) {
    const fs::directory_entry& dir_entry = *it;
    const fs::path& dir_path = it->path();
    ++it;
    std::cout << dir_entry; // UB
    std::cout << " (" << dir_path << ")" << '\n';   // UB
}
```

AFTER
```
namespace fs = std::filesystem;
fs::directory_iterator it("sandbox");
fs::directory_iterator end;
while (it != end) {
    const fs::directory_entry dir_entry = *it;
    const fs::path dir_path = it->path();
    ++it;
    std::cout << dir_entry;
    std::cout << " (" << dir_path << ")" << '\n';
}
```

https://godbolt.org/z/3Wzoq4rP4

All of the above applies to `std::filesystem::recursive_directory_iterator` as well.

_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to