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