繁体   English   中英

对 std::vector 的 emplace_back 感到困惑

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

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

如果您的移动构造函数/运算符将是 noexcept,它将改为移动它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM