Moving an object into a map

std::map::insert has 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_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);

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));

Of course, all of this is dependent on Huge having a proper R-value constructor:

Huge(Huge&& h)
{
  ...
}

Finally, you can also use std::map::emplace if you simply want to construct a new Huge object as an element in the map.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)