c++ - 对 std::vector 的 emplace_back 感到困惑
问题描述
我试图理解 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
-------
- 我认为 emplace back 会在不需要复制的情况下“就地”构建小部件?
- 为什么 emplace_back 的构造和复制既不是成对的,也不是组合在一起的?
解决方案
您在这里看到的是矢量内部增长和复制元素的效果。
如果您的移动构造函数/操作符将是 noexcept 它会移动它们。
推荐阅读
- postgresql - 代表 PostgreSQL 中的未来时间
- javascript - ScrollSpy 不工作 Bootstrap 4 和照片库不工作
- mongodb - 如何在猫鼬中多参考
- react-native - 为什么 react native app 一直在询问被删除的 main.js?
- html - 如何使用 background-image: 固定 CSS 属性打印背景?
- android - 如何在 SplashActivity 完成之前使 MainActivity 准备好?
- sql - 如何使用文字值设置包含 JSONB 元素的复合类型数组?
- javascript - 如何修复 Windows 10 中的 npm 构建错误?
- javascript - 优化汇总配置以启用摇树
- python - 打开 cv 加入最近的 Rect 轮廓