Skip to content

bugprone-unchecked-optional-access false positive #109462

@moar55

Description

@moar55

For the following snippet using std::optional monadic operations:

struct S {
  std::optional<int> a;
  std::string b;
}

void test(std::optional<S> s) {
   if (s.and_then(&S::a).has_value()) {
       std::cout << "The value is " << *s->a << std::endl;
   }
}

I get this clang-tidy warning:

unchecked access to optional value [bugprone-unchecked-optional-access]

             123 TestOptional(std::optional<S> s)
             124 {
             125   if (s.and_then(&S::a).has_value()) {
    >>>      126     std::cout << "The value is " << *s->a << std::endl;
             127   }
             128 }

This is a false positive since i do check that s, and subsequently its member a, has values, yet I get bugprone-unchecked-optional-access warning on the de-referencing of s and a.

Is this something feasible to support? Also, is it worth the effort, since we wouldn't be fully supporting emulating any lambda within the and_then, but just projections?

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