[C ++ Emplace Back vs Push Back Vector

问题描述 投票:0回答:1

我试图理解Vector C ++中的emplace_backpush_back。尽管emplace_back和push_back的整个过程都将在末尾附加数据,但据我从emplace的了解,它没有临时的异议创建。但是,当我看到日志时,两种行为都保持不变,需要帮助来了解emplace_back与push_back

#include <iostream>
#include <vector>

using namespace std;

struct Foo

{

  int myint ;

  Foo(int n) 
  {
    cout<<"constructor called "<<this<<endl;
    myint = n;
  }

  Foo(const Foo& rhs ) 
  {
    cout<<"copy constructor called "<<this<<endl;
    myint = rhs.myint;
  }

  void display() {
    cout<<"in Display Foo int = "<<myint<<endl;
  }

};


int main()
{

 cout<<"********emplace example start ********"<<endl;

  std::vector<Foo> v;

  //v.push_back(Foo(85));
  v.emplace_back(Foo(34));

  for(auto &it : v) 
  {
    it.display();
  }

  cout<<"********emplace example end ********"<<endl;

    return 0;
}

**o/p:** 
**with emplace_back**

********emplace example start ********
constructor called 0x7ffe5ae28c18
copy constructor called 0x55e02adff280
in Display Foo int = 34
********emplace example end ********

**with push_back**

********emplace example start ********
constructor called 0x7ffcb958eb68
copy constructor called 0x5611e5144280
in Display Foo int = 85
********emplace example end ********
c++ back emplace
1个回答
0
投票

emplace_back传递给它的参数传递到元素类型的构造函数以就地构造它。这就是在不创建临时对象的情况下允许使用emplace_back的原因。

您没有利用它。您仍在v.emplace_back(Foo(34));中使用表达式Foo(34)创建一个临时目录。然后,对此Foo(34)临时对象的引用将传递到Foo的(副本)构造函数以就地创建元素,但是该临时对象已在emplace_back调用之外创建。

相反,仅将参数传递给构造函数:

v.emplace_back(34);

34传递给Foo的构造函数以就地构造它而没有任何临时副本。

© www.soinside.com 2019 - 2024. All rights reserved.