Found `push_*` with move over `emplace`CXX-W2028
emplace_back and push_back are both used to add elements to a container in C++.
However, there is a difference between the two.
When push_back adds an element to the end of the container, it will first create the element,
and then "copy" or "move" the element into the container (if it is copied, it will destroy the
previously created element afterwards); while emplace_back is implemented such, that the element
is created directly at the end of the container, eliminating the need to "copy" or "move" the element.
Using the emplace_back function can reduce a copy or move construction process and improve the efficiency
of container data insertion.
Furthermore, this lint will catch cases of unnecessary temporary object creation while using emplace_back.
Exceptions
Since emplace_back is a new addition to the C++11 standard, if the program needs to take care of the
previous version of C++, you should still use push_back.
Note: this lint doesn't get raised in case of implicit constructor calls.
Bad practice
void foo() {
std::vector<int> v;
v.push_back(1); // create a temporary object and copy it into the vector
}
Recommended
void foo() {
std::vector<int> v;
v.emplace_back(2); // construct the object directly in the vector
}