[英]Confused about emplace_back of std::vector
我试图了解 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
-------
您在这里看到的是向量在内部增长和复制元素的效果。
如果您的移动构造函数/运算符将是 noexcept,它将改为移动它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.