class TestClass {
public:
TestClass(string s) {
}
};
When there is TestClass, I understand the difference between emplace and insert (emplace constructs in place while insert copies)
set<TestClass> test_set;
test_set.insert(TestClass("d"));
test_set.emplace("d");
However, if there is already a TestClass object, how are they different in terms of mechanism and preformance?
set<TestClass> test_set;
TestClass tc("e");
test_set.insert(tc);
test_set.emplace(tc);
Both are used to add an element in the container. 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.
Emplace takes the arguments necessary to construct an object in place, whereas insert takes (a reference to) an object.
insert() , emplace() and try_emplace() don't overwrite values for existing keys.
While push() function inserts a copy of the value or the parameter passed to the function into the container at the top, the emplace() function constructs a new element as the value of the parameter and then adds it to the top of the container.
emplace
does its work by perfect forwarding its parameters to the right constructor (by using likely a placement new in most of the implementations).
Because of that, in your case it forwards an lvalue reference and thus it invokes likely the copy constructor.
What's now the difference with a push_back
that explicitly calls the copy constructor?
Meyers also cites that in one of his books, and he says that there is no actual gain in calling emplace
if you already have an instance of the object.
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