llvm-project
llvm-project copied to clipboard
bugprone-unchecked-optional-access yields false-positives involving ternary operator and pointer or iterator
We encountered false-positive warnings of the check bugprone-unchecked-optional-access involving a ternary operator and an access either via a (shared) pointer or an iterator. The following example demonstrates these cases, it is also available here: https://godbolt.org/z/4zo3xn6Tx
#include <iterator>
#include <list>
#include <memory>
#include <optional>
struct A
{
A(const unsigned int p_value) :
m_value(p_value)
{}
const std::optional<unsigned int> m_value;
};
int main()
{
const A a1(1U);
// correctly identified as checked access
const unsigned int value1 = a1.m_value.has_value() ? a1.m_value.value() : 0U;
const std::shared_ptr<A> a2 = std::make_shared<A>(2U);
// wrongly identified as unchecked access
const unsigned int value2 = a2 && a2->m_value.has_value() ? a2->m_value.value() : 0U;
const std::list<A> a3{ A(3U) };
const std::list<A>::const_iterator itA3 = a3.begin();
// wrongly identified as unchecked access
const unsigned int value3 = itA3 != a3.end() && itA3->m_value.has_value() ? itA3->m_value.value() : 0U;
return EXIT_SUCCESS;
}
The warnings are:
<source>:23:65: warning: unchecked access to optional value [bugprone-unchecked-optional-access]]
const unsigned int value2 = a2 && a2->m_value.has_value() ? a2->m_value.value() : 0U;
^
<source>:28:81: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
const unsigned int value3 = itA3 != a3.end() && itA3->m_value.has_value() ? itA3->m_value.value() : 0U;
^
@llvm/issue-subscribers-clang-tidy
Just using a smart pointer without the ternary also gives the false positive. godbolt
#include <memory>
#include <optional>
int main() {
std::shared_ptr<std::optional<int>> s = std::make_shared<std::optional<int>>(3);
if (s && s->has_value())
int v1 = s->value();
}
Should be fixed with https://github.com/llvm/llvm-project/pull/120249 (checked the godbolt links and I don't see a warning anymore at trunk)