79787320

Date: 2025-10-10 12:06:10
Score: 1
Natty:
Report link

The SonarQube rule cpp:S5213 ("Functions should not be declared with a default argument value of an empty lambda expression") does not explicitly mandate that functions accepting lambdas must be implemented in the header (.h) file. Instead, it addresses a specific issue related to the use of default lambda expressions as function parameters.What cpp:S5213 is AboutThe rule flags functions that declare a default argument value for a parameter that is a lambda expression (e.g., [](){}).

The concern is that default lambda expressions can lead to unclear or unexpected behavior, as lambdas are often used for customization, and providing a default (especially an empty one) might obscure the function's intent or lead to maintenance issues.

It encourages developers to avoid default lambda arguments or to carefully consider their necessity.

Does it Imply Implementation in the .h File?No, the rule does not directly relate to where the function is implemented (header file vs. source file). It focuses solely on the declaration of the function and the use of default lambda arguments. Whether the function is implemented in a .h file (inline) or a .cpp file (separate compilation) is orthogonal to this rule. However, there are scenarios where implementing a function accepting a lambda in a header file might be relevant:Templates: If the function is a template that accepts a lambda (e.g., template<typename Func> void foo(Func&& func)), it typically needs to be defined in the header file because template definitions must be visible at the point of instantiation. This is a C++ language requirement, not a SonarQube rule.

Inline Functions: If the function is marked inline or is implicitly inline (e.g., defined within a class in a header), it would naturally reside in the .h file. But this is a design choice, not a requirement of cpp:S5213.

ExampleThe following would trigger cpp:S5213:cpp

// In header or source file

void process(int x, std::function<void(int)> callback = [](){});

The rule would flag the default empty lambda [](){}. It doesn't care whether process is implemented in a .h or .cpp file—it only cares about the default argument.To comply with cpp:S5213, you could:Remove the default lambda:cpp

void process(int x, std::function<void(int)> callback);

Or provide a meaningful default if necessary:cpp

void process(int x, std::function<void(int)> callback = [](int x){ std::cout << x; });

Key TakeawayThe cpp:S5213 rule is about avoiding default empty lambda expressions in function declarations, not about mandating where the function is implemented. The decision to place the implementation in a .h or .cpp file depends on other factors, such as whether the function is a template, inline, or part of a class, and is not influenced by this rule.

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: SIRAJOO mohammed