>
>
>
V811. Decreased performance. Excessive …


V811. Decreased performance. Excessive type casting: string -> char * -> string.

The analyzer has detected a code that can be optimized: the code contains an excessive operation when a 'std::string' object is created, and we can eliminate this.

We use the 'c_str()' function to take a pointer to a character array from the 'std::string' object. Then we construct a new object of the 'std::string' type from these characters. For instance, it can happen if the non-optimal expression is:

  • a function call argument;
  • an assignment operation operand;
  • a 'return' operation operand.

Here is a sample for the case with a function call:

void foo(const std::string &s)
{
  ....
}
....
void bar()
{
  std::string str;
  .... 
  foo(str.c_str());
}

The code is very easy to improve: you just need to remove the call of the 'c_str()' method:

....
void bar()
{
  std::string str;
  .... 
  foo(str);
}

This is a sample of incorrect code for the case with an assignment operator:

std::string str;
.... 
std::string s = str.c_str();

And this is an incorrect code for the 'return' operator:

std::string foo(const std::string &str)
{
  .... 
  return str.c_str();
}

The errors in the last two cases are fixed in the same way as with the function call.