V2012. Possibility of decreased performance. It is advised to pass arguments to std::unary_function/std::binary_function template as references.
This diagnostic rule was added at users' request.
The analyzer has detected a class inherited from 'std::unary_function' or 'std::binary_function', its template's parameters containing classes passed by value. It is obvious that passing a class object by value (especially a "heavy" object, with many fields or complex constructor) may cause additional time and memory expenses. Of course, passing an object by value is not always bad. It may make sense when you need to save an original object and work with an altered copy. But sometimes the code where an object is passed by value appears through a mistake and therefore is a bad solution.
Let's check an example. The functor we have in it will copy two objects of the 'std::string' type each time it is called instead of passing them by value:
class example : public std::binary_function
<std::string, std::string, bool>
{
public:
result_type operator()(
first_argument_type first,
second_argument_type second)
{
return first == second;
};
};
The simplest solution in this case is of course to pass the template parameters by reference instead of value:
class example : public std::binary_function
<const std::string &, const std::string &, bool> ....
Another case when the analyzer won't generate the warning is when all the arguments not passed by reference are changed in the function body:
class example : public std::binary_function
<std::string, std::string, bool>
{
public:
result_type operator()(
first_argument_type first,
second_argument_type second)
{
std::replace(first.begin(), first.end(), 'u', 'v');
std::replace(second.begin(), second.end(), 'a', 'b');
return first == second;
};
};