我正在阅读 C++11 书籍之一的建议,以便在向容器中添加项目时更倾向于emplace
避免insert
创建临时对象(调用被插入对象的构造函数/析构函数)。但我有点困惑,因为有几种可能性可以将对象添加到地图,例如
#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;
}
还有一些底层机制在阅读这样的代码时不会立即可见 - 完美转发,隐式转换......
将项目添加到地图容器的最佳方式是什么?