std::vector<std::pair<std::string, std::string> > vec;vec.emplace_back(std::string("Hello"), std::string("world"));// should end up invoking this constructor://template<class U, class V> pair(U&& x, V&& y);//without making any copies of the strings
std::map<int, Complicated> m;int anInt = 4;double aDouble = 5.0;std::string aString = "C++";
// cross your finger so that the optimizer is really goodm.insert(std::make_pair(4, Complicated(anInt, aDouble, aString)));
// should be easier for the optimizerm.emplace(4, anInt, aDouble, aString);
那么,为什么他们没有在MSVC中实现正确版本的emplace_back呢?实际上,它不久前也困扰着我,所以我在视觉C++博客上问了同样的问题。这是微软VisualC++标准库实现的官方维护者Stephan T Lavavej的回答。
Foremplace_back构造函数A (int x_arg)将被调用。对于push_backA (int x_arg)先调用,move A (A &&rhs)后调用。
当然,构造函数必须标记为explicit,但对于当前示例,最好删除显式性。
#include <iostream>#include <vector>class A{public:A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }A () { x = 0; std::cout << "A ()\n"; }A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }
private:int x;};
int main ()\{\{std::vector<A> a;std::cout << "call emplace_back:\n";a.emplace_back (0);}{std::vector<A> a;std::cout << "call push_back:\n";a.push_back (1);}return 0;}
输出:
call emplace_back:A (x_arg)
call push_back:A (x_arg)A (A &&)
// constructs the elements in place.emplace_back("element");
// creates a new object and then copies (or moves) that object.push_back(ExplicitDataType{"element"});