If checking for emptiness, suggest:
if (foo.empty())
instead of
if (foo != T()) (T == decltype(foo))
or
if (foo != "")
(And similarly for the negation, and similarly for the Yoda version of these comparisons.)
Paths
| Differential D31542
[clang-tidy] Extend readability-container-size-empty to add comparisons to newly-constructed objects ClosedPublic Authored by joshz on Mar 31 2017, 9:22 AM.
Details Summary If checking for emptiness, suggest: if (foo.empty()) instead of if (foo != T()) (T == decltype(foo)) or if (foo != "") (And similarly for the negation, and similarly for the Yoda version of these comparisons.)
Diff Detail
Event TimelineComment Actions
One way to handle this is to not suggest the fixit if the container part of the equality check is not a DeclRefExpr (perhaps after ignoring implicit casts, etc). This means the fixit won't get suggested in some cases where it otherwise could, such as: std::vector<std::string> v; if (v[0] == "") { } but it does mean that it will still catch the common cases.
joshz marked an inline comment as done. Comment ActionsResolved the bug, with a slightly modified version of Aaron's suggestion. (It will suggest parens for anything that wasn't just a DeclRefExpr, which may be a bit over-exuberant, but not as much as always suggesting them.) This revision is now accepted and ready to land.Apr 18 2017, 6:40 AM Comment Actions I don't believe I have access to commit this revision myself; can someone please do it for me? Thanks! :-) Comment Actions LG with one nit.
Comment Actions Updated to fix the nit as well as to take into account some suggestions by sbenza@ on dealing with the parentheses; IsBinaryOrTernary is based on a function he wrote at Google. PTAL.
Comment Actions
This still LGTM, so it's good to submit. Do you still need someone to land the patch for you? Comment Actions
I don't have commit access, so that would be great. Thanks!
Revision Contents
Diff 93666 clang-tidy/readability/ContainerSizeEmptyCheck.cpp
test/clang-tidy/readability-container-size-empty.cpp
|
You should pull the cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isDefaultConstructor()))) into a separate variable and reuse it instead of spelling it out four times.