The analyzer has detected a suspicious code fragment: a string variable of the 'std::basic_string' type is modified using the '+=' operator. At the same time, the right operand is an expression of arithmetic type. Due to implicit modifications that occur before the operator is called, the result may be unexpected.
Look at the example:
void foo()
{
std::string str;
str += 1000; // N1
str += ' ';
str += 4.5; // N2
str += ' ';
str += 400.52; // N3
}
A developer wanted to build a string containing three numbers. However, the execution of this code results in the following:
Note: despite the fact that both values, 1000 and 400.52, don't fit in 'char', the consequences of their conversion will be different. In the case of 1000 we are dealing with a narrow conversion. This code compiles but can be incorrect. While converting a floating-point number (400.52) to the 'char' type is undefined behavior according to the language standard.
In all such cases, it's necessary to use the appropriate functions for explicit conversion. For example, use the 'std::to_string' function to convert numbers to strings:
void foo()
{
std::string str;
str += std::to_string(1000);
str += ' ';
str += std::to_string(4.5);
str += ' ';
str += std::to_string(400.52);
}
If a developer intends to add a character to a string using its numerical representation, the readability of such code definitely decreases. It's better to rewrite such code using a character literal containing either the required character or an escape sequence:
void foo()
{
std::string str;
// first option
str += '*';
// second option
str += '\x2A';
}
The analyzer issues the following messages: