【发布时间】:2020-03-01 09:30:29
【问题描述】:
我正在尝试了解 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 ********
【问题讨论】:
-
您的测试可以使用调整。而不是
v.emplace_back(Foo(34))尝试v.emplace_back(34)