Description
Bugzilla Link | 39123 |
Version | unspecified |
OS | All |
CC | @JonasToth |
Extended Description
C++17 offers a handful of great features, one of which allows variable initializations within if and switch blocks:
- if (init; condition)
- switch (init; var)
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/