我试图了解emplace_back方法,希望它能提高性能。
对于简单的课程:
class Widget {
public:
Widget(Widget&& w) {
cout << "moving widget" << endl;
}
Widget(const Widget& w) {
cout << "copying widget" << endl;
}
Widget() {
cout << "constructing widget" << endl;
}
const Widget operator=(const Widget &w) {
cout << "copy assign widget" << endl;
return *this;
}
Widget operator=(Widget &&w) {
cout << "move assign widget" << endl;
return *this;
}
string name = "hello";
};
并且像这样使用:
vector<Widget> v { {Widget(), Widget(), Widget()} }; // 3 copy
cout << "-------" << endl;
vector<Widget> v2;
v2.emplace_back();
v2.emplace_back();
v2.emplace_back(); // why still copying?
cout << "-------" << endl;
具有输出:
constructing widget
constructing widget
constructing widget
copying widget
copying widget
copying widget
-------
constructing widget
constructing widget
copying widget
constructing widget
copying widget
copying widget
-------
您在这里看到的是矢量在内部增长和复制元素的效果。
如果您的移动构造函数/运算符为no,它将代替它们。