将对象移到地图中 [英] Moving an object into a map
问题描述
问题是大对象将被复制到地图中
The problem with this is that the huge objects will be copied into the maps
Huge huge1(some,args);
Huge huge2(some,args);
std::map<int,Huge> map1;
std::map<Huge,int> map2;
map1.insert({0,huge1});
map2.insert({huge2,0});
我如何保证搬家?这项工作还是有更多工作?
how can I guarantee a move? Will this work or is there more to it?
map1.insert({0,std::move(huge1)});
map2.insert({std::move(huge2),0});
推荐答案
std :: map: :insert
具有R值的重载:
std :: pair< iterator,bool> insert(value_type&&);
任何绑定到此重载的表达式都将调用R值构造函数。由于 std :: map< K,V> :: value_type
是 std :: pair< const key_type,mapping_type>
,并且 std :: pair
的构造函数采用R值:
Any expression which binds to this overload will invoke R-value constructors. Since std::map<K,V>::value_type
is std::pair<const key_type, mapped_type>
, and std::pair
has a constructor that takes R-values:
template<class U1, class U2>
pair(U1&& x, U2&& y);
然后您可以保证 key_type $ c的R值构造函数$ c>和
mapped_type
将在创建 pair
对象时以及在插入地图时被调用,只要您使用创建R值的表达式插入该对,例如:
then you are guaranteed that R-value constructors for key_type
and mapped_type
will be invoked, both in the creation of the pair
object, and in the map insertion, as long as you insert the pair using an expression that creates R-values, such as:
map1.insert(std::make_pair(0, Huge());
OR
map1.insert(std::make_pair(0, std::move(huge1));
当然,所有这些都取决于巨大
具有合适的R值构造函数:
Of course, all of this is dependent on Huge
having a proper R-value constructor:
Huge(Huge&& h)
{
...
}
最后,您还可以使用 std :: map :: emplace
如果您只是想构造一个新的 Huge
对象作为地图中的元素。
Finally, you can also use std::map::emplace
if you simply want to construct a new Huge
object as an element in the map.
这篇关于将对象移到地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!