Expensive return of a const
object
The return statement of a function copies an objects instead of moving it because
the returned object is declared as a const
Since R2022a
Description
This defect occurs when these conditions are true:
A function returns a
const
object, forcing a copy construction of the returned object from aconst
object.The returned object implements an available move constructor.
For instance, consider this code:
std::string foo(const std::string& str){ const std::string cstr{str}; //... return cstr; }
cstr
is constructed from a const string
. Because
cstr
is a const, the return statement copies it instead of moving it.
Polyspace® flags the declaration of cstr
.Risk
When returning objects, compilers implicitly attempt moving the returned object instead
of copying it when the object supports move semantics. When you declare an object as a
const
, this implicit move is suppressed and the compiler copies the
object. When the return statement copies the constructed return object instead of moving it,
the code becomes less efficient. Because the inefficient code compiles and behaves
correctly, the inefficiency might be difficult to diagnose.
Fix
To fix this defect, make the returned object into a nonconst.
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_RETURN_CONST_OBJECT |
Impact: Low |
Version History
Introduced in R2022a
See Also
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)