Expensive use of container's insertion method
One of the insertion methods of a container is used to insert a temporary object
Since R2022a
Description
This defect occurs when you use a container's insertion method to insert a temporary object into a container. For instance:
std::vector<std::string> v; v.push_back("foo");//Defect
insert()
push()
push_front()
push_back()
Most containers from the C++ standard template library implements these insertion methods and are supported by this checker.
Risk
When you insert a temporary object by using a container's insertion method, the compiler constructs a temporary object, and then moves or copies the object into the container. Because this insertion method requires a move or copy operation in addition to a construction, it is less efficient. Using this method results in inefficient code.
Fix
Avoid the unnecessary move or copy operation by constructing the object-to-be-inserted
in place in the container by using the container's emplace
methods. Such
methods might include emplace()
, emplace_front()
, or
emplace_back()
. Because these methods require no copy or move
operations, they are more efficient.
When using emplace
methods, avoid supplying constructor functions
manually. It is more efficient to allow the emplace
methods to construct
the object. For
instance:
std::vector<std::string> v; v.emplace_back(std::string("foo"));//Compliant but less efficient v.emplace_back("foo");// Efficient fix std::map<int, std::string> m; m.emplace(std::make_pair(5, "foo"));//Compliant but less efficient m.emplace(5, "foo");// Efficient fix
v.emplace_back(std::string("foo"))
or
m.emplace(std::make_pair(5, "foo"))
does not raise a violation of this
checker. But it is more efficient to use emplace
methods without
specifying constructor functions, such as m.emplace(5, "foo")
.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_CONTAINER_INSERTION |
Impact: Medium |
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)