cpp:S3574 should have an exception for reference return types


SonarLint SonarSource
Clion 2021.1.3
Ubuntu 20.04.3 LTS
False positive on code. Sonar tells to remove the explicit return type and rely on implicit return types.
However lambdas will never return references without explicit return types. If you want to avoid the expensive copy on some object and return a reference you are forced to use explicit return types.
Sonar should only suggest implicit return type if the return type is neither a reference, nor decltype(auto).

#include <vector>
#include <functional>
class LargeClass // avoid copying instances of this class if you can
std::vector<LargeClass> someVec;
auto getItem = [&someVec](size_t index) -> const LargeClass& { return someVec.at(index); };
std::function<const LargeClass&(size_t)> typeErasedGetter = getItem;

Hello @shojtsy,

Your report makes sense.
I personally don’t agree with this rule and recommend disabling it:

  • we have a ticket to provide an alternative new rule that would be enabled by default instead of this one.
  • We have tickets to improve this rule to handle your case: ticket1, ticket2
  • If really want to enable and follow this rule. You can return std::ref.


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