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
.
Answer
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
template
T id(T x) { return x; }
int main() {
std::set s;
s.insert(id); // OK
s.emplace(id); // error
s.emplace(id); // 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.
No comments:
Post a Comment