Open kirillbobyrev opened 6 years ago
This could/should be done with a check initialize late
that tries to reduce the scope of variables as much as possible.
The 'readability-isolate-decl' could serve as a utility function to split up declarations that can be moved to a later point
@llvm/issue-subscribers-c-17
Extended Description
C++17 offers a handful of great features, one of which allows variable initializations within if and switch blocks:
Patterns like
T Value = maybeReturnValue(); if (Value.hasValue()) // Value is never used again doSomething();
seem to be pretty common (consider llvm::Optional, std::optional, set/map::find(...) and similar operations) and it would be great to detect these (at least the easiest cases) to enforce better readability via C++17 language features.
Examples from my own code in Dex.cpp:
std::vector<std::unique_ptr> TrigramIterators;
for (const auto &Trigram : TrigramTokens) {
const auto It = InvertedIndex.find(Trigram);
if (It != InvertedIndex.end())
TrigramIterators.push_back(It->second.iterator());
}
...
std::vector<std::unique_ptr> ScopeIterators;
for (const auto &Scope : Req.Scopes) {
const auto It = InvertedIndex.find(Token(Token::Kind::Scope, Scope));
if (It != InvertedIndex.end())
ScopeIterators.push_back(It->second.iterator());
}
There's a nice blog post featuring this new language concept: https://skebanga.github.io/if-with-initializer/