我试图理解Vector C ++中的emplace_back与push_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 ********
emplace_back
传递给它的参数传递到元素类型的构造函数以就地构造它。这就是在不创建临时对象的情况下允许使用emplace_back
的原因。
您没有利用它。您仍在v.emplace_back(Foo(34));
中使用表达式Foo(34)
创建一个临时目录。然后,对此Foo(34)
临时对象的引用将传递到Foo
的(副本)构造函数以就地创建元素,但是该临时对象已在emplace_back
调用之外创建。
相反,仅将参数传递给构造函数:
v.emplace_back(34);
将34
传递给Foo
的构造函数以就地构造它而没有任何临时副本。