首页 > 解决方案 > 对 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
-------
  1. 我认为 emplace back 会在不需要复制的情况下“就地”构建小部件?
  2. 为什么 emplace_back 的构造和复制既不是成对的,也不是组合在一起的?

标签: c++stl

解决方案


您在这里看到的是矢量内部增长和复制元素的效果。

如果您的移动构造函数/操作符将是 noexcept 它会移动它们。


推荐阅读