V823. Decreased performance. Object may be created in-place in a container. Consider replacing methods: 'insert' -> 'emplace', 'push_*' -> 'emplace_*'.

The analyzer has detected a potentially inefficient method. When inserting a temporary object into a container using the methods 'insert' / 'push_*', the object is constructed outside the container and then moved/copied into the container.

On the other hand, the 'emplace' / 'emplace_*' methods allow you to eliminate the extra call of the move/copy constructor and create the object "in place" inside the container instead, perfectly passing the function's parameters to the constructor.

The analyzer suggests the following replacements:

  • insert -> emplace
  • insert_after -> emplace_after
  • push_back -> emplace_back
  • push_front -> emplace_front

Example of inefficient code:

std::string str { "Hello, World" };
std::vector<std::string> vec;
std::forward_list<std::string> forward_list;
std::list<std::string> list;
std::map<std::string, std::string> map;

....

vec.push_back(std::string { 3, 'A' });
forward_list.push_front(std::string { str.begin(), str.begin() + 6 });
list.push_front(str.substr(7));
list.push_back(std::string { "Hello, World" });
map.insert(std::pair<std::string, std::string> { "Hello", "World" });

Optimized version:

std::vector<std::string> vec;
std::forward_list<std::string> forward_list;
std::list<std::string> list;
std::map<std::string, std::string> map;

....

vector.emplace_back(3, 'A');
forward_list.emplace_front(string.begin(), string.begin() + 6);
list.push_front(str.begin() + 7, str.end());
list.emplace_back("Hello, World");
map.emplace("Hello", "World");

Sometimes replacing calls to 'insert' / 'push_*' with their 'emplace' / 'emplace_*' counterparts is not optimizing:

std::string foo()
{
  std::string res;
  // doing some heavy stuff
  return res;
}

std::vector<std::string> vec;
....
vec.push_back(foo());

In this example, the 'emplace_back' method will be as efficient as inserting the element using 'push_back'. However, the warning will be still issued for the sake of consistency. In all such cases, it will be sensible to make the replacement to keep the code consistent and avoid the reviewer's having to decide if 'emplace*' should be used or not each time they read the code. If you do not agree with this approach, you can view such warnings as false positives and suppress them.


Bugs Found

Checked Projects
374
Collected Errors
13 663