I'm reading a recommendation from one of C++11 books to prefer emplace over insert when adding items to the container in order to avoid creation of temporary objects (calls of constructors / destructors of the objects being inserted). But I'm a bit confused because there are a few possibilities how one can add an object to the map, e.g.
#include <iostream>
#include <string>
#include <cstdint>
#include <map>
int main()
{
std::string one { "one" };
std::string two { "two" };
std::map<uint32_t, std::string> testMap;
testMap.insert(std::make_pair(1, one)); // 1
testMap.emplace(2, two); // 2
testMap.insert(std::make_pair(3, "three")); // 3
testMap.emplace(4, "four"); // 4
using valType = std::map < uint32_t, std::string >::value_type;
testMap.emplace(valType(5, "five")); // 5
testMap.insert(valType(6, "six")); // 6
return 0;
}
There are also some under-the-hood-mechanisms involved which are not immediately visible when reading such a code - perfect forwarding, implicit conversions ...
What is the optimal way of adding items to the map container ?
Aucun commentaire:
Enregistrer un commentaire