False positive on lambda parameter pointer to const when lambda is assigned to function pointer

This code triggers a false positive instance of https://rules.sonarsource.com/c/RSPEC-995

using TakesPtr = void (*)(int *);

void foo()
{
    [[maybe_unused]] const TakesPtr ptr = []([[maybe_unused]] int *const arg) {};
}

The parameter cannot be pointer to const because the lambda is being converted to a function pointer with a type signature where the argument is not a pointer to const.

I suppose this is a generic problem with applying a more specific signature requirement because the functor is used in a context that puts more requirements on the involved types than the implementation itself.

This was triggered in SonarLint 6.10.0 and SonarQube 9.7.1

1 Like

Thank you for the report @torgeir.skogen!

The fact is if the issue is a false positive in the example you have presented is tightly coupled to the context of the code. To illustrate, in your reduced example code, it is possible to change the signature of the lambda, by either updating the definition of TaskPtr or changing the declared type of ptr. And I believe that performing such a change would produce better code.

I understand that performing such refactoring may not be possible or justifiable in some scenarios, for example, when the function signature is baked in some external API. In such a scenario, I agree that the above report is false-positive. However, it is nearly impossible to distinguish the issue without further context on the codebase, and we recommend marking the issue as “Won’t Fix” in the corresponding SonarQube or SonarCloud instance. This way, we do not miss the potential to improve such function pointer-based API, when all uses can be changed to accept const.