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::inserthas an overload for R-values:std::pair<iterator,bool> insert(value_type&&);Any expression which binds to this overload will invoke R-value constructors. Since
std::map<K,V>::value_typeisstd::pair<const key_type, mapped_type>, andstd::pairhas a constructor that takes R-values:then you are guaranteed that R-value constructors for
key_typeandmapped_typewill be invoked, both in the creation of thepairobject, and in the map insertion, as long as you insert the pair using an expression that creates R-values, such as:OR
Of course, all of this is dependent on
Hugehaving a proper R-value constructor:Finally, you can also use
std::map::emplaceif you simply want to construct a newHugeobject as an element in the map.