调用std :: map :: emplace()并避免不必要的构造 [英] Calling std::map::emplace() and avoiding unnecessary constructions
问题描述
我有一个 std :: map
,它的键是 std :: string
,值是我自己定义的类型。
让我们假设我有以下代码:
std :: map< std :: string,MyType> mymap;
std :: string str1(test);
MyType value(pars); //我想要移动值
mymap.emplace(std :: make_pair(str1,std :: move(value))); // A
mymap.emplace(str,std :: move(value)); // B
假设 std :: map
存储对,我想A会生成进一步调用 std :: pair
构造函数( make_pair
),调用 std :: pair
移动构造函数(具有右值参数的就地构造)。
只会产生对 std :: pair
构造函数的调用。
所以我们可以说B比A优先为了避免不必要的构造?
根据 http://www.cplusplus.com/reference/map/map/emplace/ :
如果一个新元素的键是唯一的,则在地图中插入一个新元素。这个新元素是使用args作为构造一个value_type(这是一个对类型的对象)的参数构造的... ...通过调用allocator_traits :: construct,args转发来构造元素。 p>
所以在选项A中,你首先构造一个 emplace
选项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/:
Inserts a new element in the map if its key is unique. This new element is constructed in place using args as the arguments for the construction of a value_type (which is an object of a pair type) ... The element is constructed in-place by calling allocator_traits::construct with args forwarded.
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()并避免不必要的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!