Skip to content

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

Closed
@sapi33

Description

@sapi33

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions