llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

bugprone-unchecked-optional-access yields false-positives involving ternary operator and pointer or iterator

Open sapi33 opened this issue 3 years ago • 3 comments

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;
                                                                                ^

sapi33 avatar Apr 03 '23 10:04 sapi33

@llvm/issue-subscribers-clang-tidy

llvmbot avatar Apr 03 '23 14:04 llvmbot

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();
}

AMS21 avatar Apr 05 '23 07:04 AMS21

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)

jvoung avatar Mar 19 '25 01:03 jvoung