我正在尝试理解Vector C++中的emplace_back
与push_back
。尽管template_back和push_back的整个过程都是在最后添加数据,但据我从template了解,它没有临时的异议创建。但是当我看到日志时,两种行为保持不变,需要帮助理解template_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
的构造函数,以便在没有任何临时副本的情况下就地构造它。