Fan
Fan

Reputation: 133

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?

Upvotes: 9

Views: 2943

Answers (1)

songyuanyao
songyuanyao

Reputation: 172884

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.

Upvotes: 11

Related Questions