I was wondering if it is OK to always use emplace
to replace insert
when inserting a single element into a STL container, like set, unordered_set?
From the signature, emplace
is simpler and do not involve overloads. Is there any issue with stop using insert
and use emplace
all the time?
Note: there are SO questions asking about the difference between emplace
and insert
/push_back
etc. (e.g. here, here, and here) I understand the difference, and it seems to me that emplace
is better in every way. I just want to confirm if it's OK to deprecate insert
.
The advantage of emplace is, it does in-place insertion and avoids an unnecessary copy of object. For primitive data types, it does not matter which one we use. But for objects, use of emplace() is preferred for efficiency reasons.
The primary difference is that insert takes an object whose type is the same as the container type and copies that argument into the container. emplace takes a more or less arbitrary argument list and constructs an object in the container from those arguments.
C++ Vector Library - emplace() Function The C++ function std::vector::emplace() extends container by inserting new element at position. Reallocation happens if there is need of more space. This method increases container size by one.
With the simple benchmark here, we notice that emplace_back is 7.62% faster than push_back when we insert 1,000,000 object (MyClass) into an vector.
There are some examples here that can be adapted to emplace
and insert
, showing when the behaviour may differ.
These examples may seem a bit artificial, so I'll give one that will hopefully appear less so:
#include <set>
template <typename T>
T id(T x) { return x; }
int main() {
std::set<int(*)(int)> s;
s.insert(id); // OK
s.emplace(id); // error
s.emplace(id<int>); // OK
}
insert
can deduce the template parameter of id
because it knows what type it wants. For emplace
you get an error unless you explicitly specify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With