将对象移到地图中 [英] Moving an object into a map

查看:54
本文介绍了将对象移到地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是大对象将被复制到地图中

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆