False-positive cpp:S6024: triggered on free function

Hi o/

I think I’ve got something that is clear false positive:

You can clearly see that marked function is just generic free function for containers, and yet I’ve got an error that says that I should prefer free functions over method. Seems like clear false-positive.

JK

Hello @koniarik,

Welcome to the community!

I don’t think the case is a false positive. It is actually the opposite. Your example shows the value of the rule.

In your case, the rule is highlighting cont.size() and saying that you should prefer the free function over the member function. In your case, the rule is suggesting changing it to std::size(cont).

The rule suggests that because free function like std::size should work with containers that don’t have a member function like C-style arrays.

In your case, you are handling C-style arrays explicitly which is not needed if you use std::size. So the rule is suggesting that you refactor your function to:

[[nodiscard]] constexpr std::size_t cont_size( const Container& cont ) noexcept {
  if constexpr ( static_sized< Container > ) {
     return std::tuple_size_v< Container >;
  } else {
     return std::size(cont);
  }
}

Optional

If you want, you can take it a step further and have a size free function that works by default with static_sized container you can define a free size function that works only with static_sized container. this way can refactor your function to:

// assuming we have this in an included generic header file
namespace example {
  template <typename Container>
    requires static_sized<Container>
  [[nodiscard]] std::size_t size(const Container& _Cont) {
    return std::tuple_size_v<Container>;
  }
}

// new implementation
[[nodiscard]] constexpr std::size_t cont_size(const Container& cont) noexcept
{
  using example::size;
  using std::size;
  return size(cont);
}

Let me know if it is clearer now.

Thanks a lot for the answer!

Yeah, the code smell makes sense once I look at it the way you described, what confused me in the end is that from GUI, it was not obvious that the report refers to the line with cont.size():

I thought it relates to the cont_size function itself given that the warning is above it.

Thanks for explaining this!

JK

P.S: maybe… do you think you cold write the name of offending method in the error message? something like: Prefer free functions over member functions (“cont.size()”) when handling objects of generic type “Container”.

I think I noticed a difference here,

if I open the issue “Issues” tab for the main branch of the repository, the warning shows exactly the line of the code that bothers it (in this case: cont.size()).

But same did not happend in the “Code” tab and hence my misunderstanding.

I have to remember that :slight_smile:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.