Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Set emplace vs insert when an object is already created

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);
like image 815
MaxHeap Avatar asked Apr 22 '16 14:04

MaxHeap


People also ask

Is emplace better than insert?

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.

Is emplace the same as insert?

Emplace takes the arguments necessary to construct an object in place, whereas insert takes (a reference to) an object.

Does map emplace overwrite?

insert() , emplace() and try_emplace() don't overwrite values for existing keys.

What is the difference between emplace and push?

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.


1 Answers

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.

like image 99
skypjack Avatar answered Oct 05 '22 10:10

skypjack