bugprone-unchecked-optional-access false-positive with absl::nullopt comparison
On clang-tidy at bdb859c9a75f0e574ac877c4ca277edcc6db4e46, I believe bugprone-unchecked-optional-access has a false-positive.
$ $clang_tidy '-checks=-*,bugprone-unchecked-optional-access' file_name.cpp -- clang++ -x c++ -std=c++17 file_name.cpp
file_name.cpp:19:52: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
return (optional_value != absl::nullopt) ? *optional_value : 0;
Creduce'd repro:
namespace absl {
namespace a {
enum au { av };
template <au> class aw {};
template <au> class ax {};
template <typename> struct ay { static constexpr au az = av; };
template <typename> struct b { static constexpr au az = av; };
} // namespace a
struct nullopt_t {
} nullopt;
template <typename am>
class optional : a::aw<a::ay<am>::az>, a::ax<a::b<am>::az> {
public:
am operator*();
};
template <typename am> bool operator!=(am, nullopt_t);
} // namespace absl
int c(absl::optional<int> optional_value) {
return (optional_value != absl::nullopt) ? *optional_value : 0;
}
Note that if the condition is changed to return optional_value ? *optional_value : 0; (and explicit operator bool() const; is added to the optional class above), the diagnostic is not issued.
cc @ymand
@llvm/issue-subscribers-bug
@llvm/issue-subscribers-clang-tidy
Comparisons to std::nullopt are also not being taken into account.
https://godbolt.org/z/xKdqhTsaM
#include <optional>
void sinc(int);
void fun(std::optional<int> opt) {
if (opt != std::nullopt) {
sinc(*opt); // <source>:7:15: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
}
}
Patch to add support for operator== and operator!=: https://reviews.llvm.org/D139360
Fixed in commit 390029be8946cac807e8fc978b9cf3790e7456cc.