<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/128705>128705</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[clang-tidy] Check request: bugprone-avoid-dangling-in-std-filesystem
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang-tidy
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
denzor200
</td>
</tr>
</table>
<pre>
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.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzcVcGO2zYQ_ZrxZWCDHlmWfNBB3l0d2yJt0WNAiWOJXZpUSMpb79cXlL3rbbJJkUMuAQyIMvVm3ptHPMoQdG-ZK8j3kN8v5BQH5yvF9tl5EmLROnWuQNS_MKuAEruBu0eMg4z4pI3Bg7YKpyB7RndAbU_SaCUjK_R8YM-244DRYXBHjoO2_RUrA7onywrbM8JWhKggqyGrD9pwOIfIx8u70p676Pz5o47sZXQetgJbPjjPGAe-tdTOrvB3bTv-_oJARUBtO89HthEHOXO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