C++ S6023: False positive on optional<NonCopyable>

Environment:

  • SonarLint 5.3.0.36775 SonarSource
  • Clion 2021.1.3
  • Ubuntu 20.04.3 LTS

False positive on code, suggesting refactoring to a version which would be ill-formed.
The method optional::value_or returns by value and relies on copying, so only applicable for cases when the embedded type is copyable. The rule should only trigger if the refactored code would be valid.

#include <optional>
#include <memory>
#include <variant>
#include <string>

struct ExampleBase {
};

using NonCopyable = std::variant<std::string, std::unique_ptr<ExampleBase>>;

NonCopyable clone(const NonCopyable&) {
  return NonCopyable("mock"); /* function body is mocked, real one would visit the polymorphic type  */
}

using OptionalNonCopyable = std::optional<NonCopyable>;

NonCopyable cloneOrDefault(const OptionalNonCopyable & opt, const NonCopyable& nc)
{
  return clone(opt ? *opt : nc);  // false positive on this line
}

Hello @shojtsy,

Welcome to the Community!

Thanks for the detailed and valuable report. You are right this is a clear false-positive.
I created this ticket to fix it. Feel free to watch it for updates.

Thanks,

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