Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ emplace_back parameters

Here is a piece of code in my daily work. I just want to ask you if there is any difference between the two cases, especially in terms of performance.

std::vector< std::pair<std::string, std::string> > aVec;

// case 1
aVec.emplace_back("hello", "bonjour");

// case 2
aVec.emplace_back(std::pair("hello", "bonjour"));

Following question:

What about a std::list for these two cases?

like image 364
Fan Avatar asked Apr 07 '17 08:04

Fan


People also ask

What is Emplace_back in vector?

C++ Vector Library - emplace_back() Function The C++ function std::vector::emplace_back() inserts new element at the end of vector. Reallocation happens if there is need of more space. This method increases container size by one.

Is Emplace_back faster than Push_back?

With the simple benchmark here, we notice that emplace_back is 7.62% faster than push_back when we insert 1,000,000 object (MyClass) into an vector.

When should I use Emplace_back?

Specific use case for emplace_back : If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back . It will create the object in-place within the container.

Does Emplace_back make a copy?

So you can emplace_back does use the desired constructor to create the element and call copy constructor when it need to grow the storage. You can call reserve with enough capacity upfront to avoid the need to call copy constructor.


1 Answers

emplace_back will construct the element in-place, the argument passed in will be perfect-forwarded to the constructor for the element.

For the 1st case, conceptually only one step is needed, i.e. the appropriate constructor of std::pair will be invoked to construct the element directly in vector.

For the 2nd case, three steps is needed; (1) the appropriate constructor will be invoked to construct a temporary std::pair, (2) the element will be move constructed in vector in-place from the temporary std::pair, (3) the temporary std::pair is destroyed.

like image 110
songyuanyao Avatar answered Oct 21 '22 22:10

songyuanyao