问题描述
我有一个
选项B向前移动 str ,并将 std :: move(value)返回到对的构造函数。
所以是的,选项A构造2对,而选项B只构造1。
I have a std::map whose keys are std::string and values are my own defined type.
Let's suppose I have the following code:
std::map<std::string, MyType> mymap; std::string str1("test"); MyType value(pars); //I want value to be moved mymap.emplace(std::make_pair(str1, std::move(value))); //A mymap.emplace(str, std::move(value)); //B
Assuming std::map stores pairs, I guess A would generate a further call to std::pair constructor (make_pair), followed by another call to std::pair move constructor (in-place construction with rvalue argument).
And I think B would just generate a call to std::pair constructor.
So can we say B is preferred over A in order to avoid unnecessary constructions?
According to http://www.cplusplus.com/reference/map/map/emplace/:
So in option A, you first construct a pair which emplace will forward to the constructor (as an rvalue) for pair which will then do a move construction.
Option B forwards str and the return of std::move(value) to the constructor for pair.
So yes, option A constructs 2 pairs while option B only constructs 1.
这篇关于调用std :: map :: emplace()并避免不必要的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!