简体   繁体   English

C ++ \\ templace_back参数

[英]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? 这两个案例的std :: list怎么样?

emplace_back will construct the element in-place, the argument passed in will be perfect-forwarded to the constructor for the element. emplace_back就地构造元素,传入的参数将完美地转发给元素的构造函数。

For the 1st case, conceptually only one step is needed, ie the appropriate constructor of std::pair will be invoked to construct the element directly in vector . 对于第一种情况,概念上只需要一步,即调用std::pair的适当构造函数直接在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. (1)将调用适当的构造函数来构造一个临时的std::pair ,(2)该元素将在临时std::pair就地vector移动构造,(3)临时std::pair是销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM