Unnecessary copy caused by type conversion
Mismatched type between const reference and its initializer
results in unnecessary copy
Since R2026a
Description
This defect occurs when the type of the initializer of a const
reference is not an exact match but is compatible with the type of the reference. For
example, consider this
code
std::map<std::string, std::string> myMap;
for(const std::pair<std::string, std::string> &element : myMap) {
//...
}const reference
element is std::pair<std::string, std::string>.
This reference is initialized by elements of the std::map object
myMap, which has the type std::pair<const std::string,
std::string>. The type of element is not an exact match
with the type of the elements of myMap. An object with the exact
required type is constructed by copy from the initializer. Polyspace® reports a defect.Risk
When the type of a const reference is compatible with but is not
an exact match of the type of the initializer, the compiler makes a copy of the
initializer that has the exact same type as the reference. The reference points to this
copy. For example, in the preceding code, element points to copies of
the elements of myMap instead of pointing to the elements themselves.
Copying the initializer in such cases is unexpected and can be expensive.
Fix
To fix this defect, avoid type mismatch when declaring a reference. Use the
auto keyword whenever possible. This way, the compiler deduces the
correct required type. For
example:
std::map<std::string, std::string> myMap;
for(auto &element : myMap) {
//...
}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:
EXPENSIVE_COPY_FROM_TYPE_CONVERSION
|
| Impact: Medium |
PQL Name:
std.defects.EXPENSIVE_COPY_FROM_TYPE_CONVERSION
|
Version History
Introduced in R2026a
See Also
Find defects
(-checkers) | Expensive local
variable copy | Reference to un-named
temporary
Topics
- Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Polyspace Results Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)
- Expensive-to-Read Objects in Bug Finder