Unnecessary construction before reassignment
Instead of directly constructing objects with value, you construct objects and then immediately assign values to objects
Since R2023a
Description
Polyspace® reports this defect if you construct a local object and then you immediately assign a value to the object in the same scope. For example:
class obj{/*...*/}; void foo(obj a){ obj b; b = a; //Defect }
b
and reassign
a
to b
without using b
. This is
inefficient and Polyspace reports a defect. Polyspace flags the unnecessary construction of both trivial and nontrivial
objects.Risk
Construction and immediate reassignment of an object requires two calls:
Call to the constructor of the object.
Call to the assignment operator.
When the assignment operator reconstructs the object, the code immediately discards the previously constructed value. The immediate reassignment makes the constructor call unnecessary. Because the code compiles and behaves correctly, you might not detect the unnecessary construction, making the code inefficient.
Fix
To resolve this defect, directly construct the object with the value by using the copy or move constructor. For instance:
class obj{/*...*/}; void foo(obj a){ obj b{a}; }
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_CONSTRUCTION_BEFORE_ASSIGNMENT |
Impact: Low |
Version History
Introduced in R2023aSee 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)