Wrong suggestion to use pointer to const

Hi @torgeir.skogen,
Thank you for reporting the suspected false positive. In this case, I do not consider it to be a false positive, because your code fails to compile:

error: no matching conversion for functional-style cast from ‘int *const’ to ‘Bar’

Given the code is incorrect from a C++ compiler point of view, our analyzer does its best to interpret the intent and report the potential issues once the code is fixed. Surely enough, it often fails to do so. However, it does flag the code with a special issue.

There is a rule with ParsingError as a key. You can enable this rule (through the SonarLint JSON setting or in your SQ instance) to make sure that there is no parsing error in the code where the false positive is happening. For example, in SonarLint for VisualStudio, you can put the following into your settings.json:

{
  "sonarlint.rules": {
    "cpp:ParsingError": {
      "level": "On"
    },
    "c:ParsingError": {
      "level": "On"
    }
  }
}

You can fix foo1 either the way you did in foo2 or by adding a constructor to Bar that would take a non-const pointer. Both fixes also remove the S995 report.

However, you mentioned that you’ve encountered the FP in a more complex piece of code. I encourage you to get back to your original code and check if it contains a ParsingError. If it does not, besides trying to simplify it again and watching to not introduce a ParsingError, you can generate a reproducer file:

  • Add the reproducer option to the scanner configuration:
    sonar.cfamily.reproducer= “Full path to the .cpp file that has or include the file that has the false-positive”
  • Re-run the scanner to generate a file named sonar-cfamily.reproducer in the project folder.
  • Please share this file. If you think this file contains private information you can send it privately.