std::function parameter where a template parameter would do
ID |
c.performance.std_function_parameter |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Inefficient Call |
Language |
C / C++ |
Description
This parameter takes a callable by std::function, which type-erases it: the callable is heap-allocated when it does not fit in the small-buffer optimization, and every call goes through an indirect call the compiler usually cannot inline. When the callable’s concrete type is known at the call site, take it as a template parameter instead — the compiler can then inline the call directly, with no allocation and no indirection.
Rationale
This parameter takes a callable by std::function, which type-erases it: the callable is heap-allocated when it does not fit in the small-buffer optimization, and every call goes through an indirect call the compiler usually cannot inline. When the callable’s concrete type is known at the call site, take it as a template parameter instead — the compiler can then inline the call directly, with no allocation and no indirection.
The following code illustrates the pattern detected by this rule:
// FLAGGED: std::function parameter where a template parameter would do
void run(std::function<void(int)> callback)
{
callback(1);
}