Search code examples
c++insertsetemplace

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);

Solution

  • 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.