Expensive use of std::string
with empty string
literal
Use of std::string
with empty string literal can be replaced by
less expensive calls to std::basic_string
member functions
Since R2021a
Description
In your C/C++ code, the checker flags these operations:
Constructing an instance of
std::string
by using an empty string literalAssigning an empty string literal to an instance of
std::string
Comparing an instance of
std::string
to an empty string literal
Usage notes and limitations:
The checker does not track the origin of
const char
pointer variables that are empty and are eventually used withstd::string
.This checker is partially obsolete when you use current compilers. Compilers such as GCC 5.1 and Visual Studio® 2015 optimize out construction from an empty string literal and treat it as identical to the default construction.
Risk
The preceding operations can be replaced by calls to the default constructor and the
empty
and clear
member functions of the
std::basic_string
class template. Certain compilers might generate
additional instructions for the explicit operations compared to the use of the built-in
member functions. The use of these operations might reduce the performance of the compiled
code.
Fix
Replace explicit operations involving empty string literals by these calls to the
default constructor and member functions of std::basic_string
.
Do not Use | Use |
---|---|
std::string s("");
|
std::string s;
|
std::string s = "";
|
std::string s;
|
s = "";
|
s.clear();
|
if (s == "")
|
if (s.empty())
|
return "";
|
return {};
|
void foo(const std::string& s = ""); | void foo(const std::string& s = {}); (C++11) or
foo(const std::string &str2 = std::string()) |
foo(""); | foo({}) (C++11) or
foo(std::string()) |
Class::Class() : str("") {//...} | Class::Class() : str() {//...} |
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
UNNECESSARY_EMPTY_STRING_LITERAL |
Impact: Low |
Version History
Introduced in R2021a
See Also
Find defects
(-checkers)
| Expensive constant
std::string construction
| Expensive
std::string::c_str() use in a std::string operation
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)