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

class TestClass { public: TestClass(string s) { } }; 

When there is a TestClass, I understand the difference between emplace and insert (mount constructions in place while inserting copies)

  set<TestClass> test_set; test_set.insert(TestClass("d")); test_set.emplace("d"); 

However, if there is already a TestClass object, how do they differ in terms of mechanism and preliminary work?

  set<TestClass> test_set; TestClass tc("e"); test_set.insert(tc); test_set.emplace(tc); 
+5
source share
2 answers

emplace does its job, improving the transfer of its parameters to the right constructor (using the likely placement of a new one in most implementations).
Because of this, in your case, it forwards the lvalue reference and therefore calls the probable copy constructor.
What is the difference with push_back , which explicitly calls the copy constructor?

Myers also cites this in one of his books, and he says that there is no real win when calling emplace if you already have an instance of the object.

+5
source

Careful use of emplace allows you to create a new element, avoiding unnecessary copy or move operations. The constructor of the new element is called with exactly the same arguments as for emplace, redirected via std :: forward (args) ....

The link here leads me to believe that such non-โ€œcareful useโ€ will result in very similar mechanism and performance as insert, the exact details of which may be specific to the compiler.

+2
source

Source: https://habr.com/ru/post/1247728/


All Articles