Main Content

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
}
This code is inefficient because you construct the object 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:

  1. Call to the constructor of the object.

  2. 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

expand all

In this example, the functions func1() and func2 construct an object and then immediately reassign the value. Using two statements for construction and reassignment is inefficient. Polyspace reports defects on the reassignment statements.

#include <string>
#include <unordered_set>
#include <vector>

typedef std::unordered_set<std::string> Type1;
typedef std::vector<std::string> Type2;

template< typename T >
T factory();

void func1(){
    Type1 obj;
    obj = factory< Type1 >(); // Defect 
}

void func2(){
    Type2 obj;
    obj = factory< Type2 >(); // Defect 
}
Correction — Construct Objects by Using Value

To fix this defect, combine the constructor and assignment statements into one statement:

#include <string>
#include <unordered_set>
#include <vector>

typedef std::unordered_set<std::string> Type1;
typedef std::vector<std::string> Type2;

template< typename T >
T factory();

void func1(){
    Type1 obj = factory< Type1 >(); //No defect   
}

void func2(){
    Type2 obj = factory< Type2 >(); //No defect
}

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: UNNECESSARY_CONSTRUCTION_BEFORE_ASSIGNMENT
Impact: Low

Version History

Introduced in R2023a

expand all